I have some C++ code compiling depending on some #define
. Today I mistakenly forgot to #include
the file with the defined, which lead to my program being compiled with the wrong code.
What are my options to get rid of this potential error?
I have some C++ code compiling depending on some #define
. Today I mistakenly forgot to #include
the file with the defined, which lead to my program being compiled with the wrong code.
What are my options to get rid of this potential error?
Most compilers let you define preprocessor macros within the compilation command line. For instance, g++ and clang++ have -DMACRO=VALUE
.
trunit.cpp
:
#include <iostream>
int main() {
#ifdef ALT_FOO
std::cout << "BAR\n";
#else
std::cout << "FOO\n";
#endif // ALT_FOO
}
In the current situation you're in, this code's behaviour would depend on the inclusion of a header file defining or not the macro ALT_FOO
. You can control that from the build process itself:
$ # build the FOO variant:
$ g++ -Wall -Wextra -Werror -pedantic -O2 trunit.cpp -o foo
$ ./foo
FOO
$ # build the BARvariant:
$ g++ -Wall -Wextra -Werror -pedantic -O2 -DALT_FOO trunit.cpp -o foo
$ ./foo
BAR
Have the macro header either #define FOO
or #define NFOO
.
You would then test for exactly one of FOO
or NFOO
to be defined
#if defined(FOO) && defined(NFOO)
#error both FOO and NFOO defined
#elif defined (FOO)
// foo case
#elif defined (NFOO)
// not foo case
#else
#error neither FOO nor NFOO defined
#end