我有一些根据某些#define
进行编译的C ++代码。今天,我错误地忘记了#include
具有定义的文件,这导致我的程序使用错误的代码进行编译。
要摆脱这种潜在的错误,我有什么选择?
答案 0 :(得分:5)
大多数编译器使您可以在编译命令行中定义预处理器宏。例如,g ++和clang ++具有-DMACRO=VALUE
。
trunit.cpp
:
#include <iostream>
int main() {
#ifdef ALT_FOO
std::cout << "BAR\n";
#else
std::cout << "FOO\n";
#endif // ALT_FOO
}
在当前情况下,此代码的行为将取决于是否包含定义宏ALT_FOO
的头文件。您可以从构建过程本身进行控制:
$ # 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
答案 1 :(得分:2)
使宏头为#define FOO
或#define NFOO
。
然后您将测试要定义的FOO
或NFOO
中的一个正好
#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