Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting static constant value (not by preprocessor) at compile time

just short question. I can define preprocessor variables at compile time, using -D flag for g++. But is there a way to set value of normal constant variable this way?

I want to avoid preprocessor. I don't see any reason, why this couldn't be possible.

like image 386
Krzysztof Stanisławek Avatar asked Dec 13 '25 23:12

Krzysztof Stanisławek


1 Answers

Well, you cannot define a variable from a compiler switch. You can fake it though:

const int my_cli_defined_variable = MY_CLI_DEFINED_VARIABLE
#undef MY_CLI_DEFINED_VARIABLE

and then:

g++ -DMY_CLI_DEFINED_VARIABLE=5 …

The second line will make sure that the preprocessor macro won't be used by accident by your real code, because the macro won't exist anymore. So, the only way to use this CLI-defined variable will be in a type-safe way through the const variable.

A full example that takes care of the situation when the macro is not defined:

const int my_cli_defined_variable = 
#ifdef MY_CLI_DEFINED_VARIABLE
    MY_CLI_DEFINED_VARIABLE;
#undef MY_CLI_DEFINED_VARIABLE
#else
    42;
#endif
like image 87
liori Avatar answered Dec 15 '25 12:12

liori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!