If I had to run functions in the global scope e.g. in order to populate a static container in several cpp-files, then each time such a function is invoked I would have to initialize a new variable as well, even though I do not need them.
Here is a simplified example for such dummy variables.
static bool foo() { /*some code*/ return true; }
static bool foo2() { /*some code*/ return true; }
static bool bDummy1 = foo();
static bool bDummy2 = foo2();
Technically bDummy1
and bDummy2
are superfluous, but because of the C++ syntax it is still required. Why is there no other way to solve this?
I know it creates very little overhead to create such superfluous variables and the static
keyword makes them only locally visible in cpp-files, but that is still not a good coding style.
each time such a function is invoked I would have to initialize a new variable as well
You don't need several variables by TU, only one is sufficient:
static bool bDummy1 = foo();
static bool bDummy2 = foo2();
can be replaced by
static bool bDummy = foo(), foo2();
Why is it not possible to invoke functions globally without initializing new variables?
gcc/clang have __attribute__ ((constructor))
to solve that issue