Best Practices for Storing C++ Program Parameters

cconfigurationparametersprogramming practices

I'm currently developing a project which has multiple c++ programs communicating over IPC to each other. Each of these programs will rely on some parameters to run and these may be common to several programs, e.g.parameters for camera calibration, minNeighbours, scaling factor, etc.

I am wondering what the best practices are for achieving this. Solutions being considered at this stage are:

  1. Hardcoding the values in – obviously not good if I should ever want to change the values of the parameters.

  2. Include a constants.hpp file containing const [int] variable definitions – my current solution.

  3. A config.txt file which can be parsed by each program at its start-up – can multiple programs safely open and read files concurrently.

  4. Preprocessor directives, i.e. #define.

I can implement any solution, I'm really looking for guidance on best practices.

Best Answer

Only load a constant from a config-file or other runtime-config-source if it actually makes sense to execute the program with different values for the parameter.
Consider supporting a default if not provided by the config where it makes sense.

Needlessly exporting a compile-time-constant into a run-time-config makes for more complicated and less efficient code which can go wrong in more ways than before. Desist.

When should you name a compile-time-costant?

  • If it has some semantic meaning beside it happening to have a specific value, meaning you should have a good semantic instead of descriptive name for it.
  • If you use it to tune your code. These constants nearly always also fall under the other point.
Related Topic