i have a situation in C++ where i need to:
1) define a “default” value for static const variables in a namespace declared/defined in an object module
2) allow several “main” programs to “overwrite” these values using “custom” values
each “main” program has its own build folder and its own copy of the object module, so “main” programs are completely independent of each other:
e.g.
/mainProgramA/build/mainProgramA.o
/mainProgramA/build/Module.o
/mainProgramB/build/mainProgramB.o
/mainProgramB/build/Module.o
also, at any one time, either the default values or custom values will be defined/declared, but not both. if the compiler “finds” the custom values, they will be used, if not, the defaults will be used.
i can’t use weak symbols without namespaces because i need the namespaces to avoid naming clashes. i can’t use weak symbols with namespaces because i get “error: weak declaration of … must be public”. i could use a class perhaps, but all the values are known at compile time and not variable. What is the simplest and most elegant way to do this?
to clarify, i’m trying to do something like this:
DefaultValues.h:
namespace ConfigParams {
static const int param1 = 1;
static const int param2 = 2;
}
CustomValues.h:
namespace ConfigParams {
static const int param1 = 100;
static const int param2 = 200;
}
Module.h:
#include "DefaultValues.h"
class Module {
public:
static void printParam1();
}
Module.cpp:
#include "Module.h"
void Module::printParam1()
{
printf("%d\n", param1);
}
mainUsingDefaultValues.cpp (which will link in a copy of module.o where param1 == 1):
#include "Module.h"
...
Module::printParam1(); // Should print "1"
mainUsingCustomValues.cpp (which will link in a copy of module.o where param1 == 100):
#include "CustomValues.h"
#include "Module.h"
...
Module::printParam1(); // Should print "100"
You can make it more flexible if you need it.
EDIT: Just in case I misunderstood the question. This way user of your library will be defaulted to
DefaultValues.h, unless they includeCustomValues.hbeforeModule.h. You can have either one or another, but not both.will not compile, since you’ll be redefining your constants.
And just to make sure, you’ll need to include
CustomValues.hinModule.cppas well. So, probably, it’s better to make a#ifdefswitch insideModule.hand make user#define MY_CUSTOM_VALUESsomewhere before anyModule.hincludes: