Question

I am currently working in an aleady developed C++ project. The existing files are the following:

-main.cpp
-HydroModel.cpp
-ODESys.cpp

-HydroModel.hpp
-ODESys.hpp
-ODESysSol.hpp

In the file HydroModel.hpp there are some constants defined in the namespace config, for example

 namespace config 
 { 
     const unsigned int dim = 40; 
     const unsigned int NaN = 10101; ... 
 }

This file is being included in main.cpp, ODESysSol.hpp and HydroModel.cpp. These constants are being used over and over in those files.

However, these constants are not always the same, as they change depending on the case study analyzed. The idea is to take out these variables into a txt file in order to avoid compiling each time that the case study changes.

I know it would be easy if the variables are being defined inside a function or the main(), but so far I didn't find a way to do it in the preprocessor.

Is it possible to load the txt file and define the variables inside the namespace or I have to rewrite everything that is related to those variables?

Was it helpful?

Solution

Change your header file HydroModel.hpp to

namespace config 
{ 
    extern unsigned int dim; 
    extern unsigned int NaN;
}

In HydroModel.cpp write

namespace config 
{ 
    unsigned int dim; 
    unsigned int NaN;
}

That way, you won't have to rewrite much of your existing code.

Now all what remains to you is to implement a function which initializes those variables from the text file. Afterwards make sure this function is called when the program starts, before any other code tries to access the variables.

OTHER TIPS

If you want to "avoid compiling", then it has to be data loaded at runtime. It can't be something from a global compile-time const variable. You can have an object with (perhaps static) functions that return these values as loaded from a file. I suggest functions rather than exposing variables directly to prevent the outside world from modifying their values.

But they can't just be global const variables.

If you want to avoid recompiling, then some config file that would be loaded at runtime needs to be used.

You can also use ifdef and then use preprocessor directives in project files to choose the value of a constant, but that requires recompiling.

Licensed under: CC-BY-SA with attribution
scroll top