Jer*_*ner 6 c++ conditional-compilation language-lawyer c-preprocessor
今天我遇到了一些包含#ifdef子句的C++代码,如下所示:
#ifdef DISABLE_UNTIL OTHER_CODE_IS_READY
foo();
#endif
Run Code Online (Sandbox Code Playgroud)
请注意"DISABLE_UNTIL"和"OTHER_CODE_IS_READY"之间的空格.基本上#ifdef行中指定了两个标记.
我的问题是,这是合法的C++代码吗?(g ++编译它没有任何错误,它显然只是忽略了第二个标记).如果它是合法的,第二个令牌是否会产生任何影响?
abe*_*nky 12
您发布的语法不合法,其含义不明确.
根据您希望实现的目标,您可以使用||或&&组合它们吗?
(当然如果这是别人的代码,我会拒绝它为不合适/不可用)
#if defined(DISABLE_UNTIL) || defined(OTHER_CODE_IS_READY)
foo();
#endif
Run Code Online (Sandbox Code Playgroud)
[C++11 16.1],[C++11 16.5]并顺便说一下,[C99 6.10.1/4]所有这不能不说是无效的.
if-group:
# ifconstant-expression new-line group opt
# ifdefidentifier new-line group opt
# ifndefidentifier new-line group opt
只有一个标识符是合法的.
海湾合作委员会自己的文件同意.
我自己的测试表明,只有第一个标识符被接受,第二个标识符被简单地丢弃; 这可能是为了简化实现,但标准确实需要在这里进行诊断,所以当你使用-pedantic至少†标志时你应该看到这一点.
#include <iostream>
using namespace std;
#define A
#define B
int main() {
#ifdef A
std::cout << "a ";
#endif
#ifdef B
std::cout << "b ";
#endif
#ifdef C
std::cout << "c ";
#endif
#ifdef B C
std::cout << "bc ";
#endif
#ifdef C B
std::cout << "cb ";
#endif
return 0;
}
// Output: "a b bc"
// Note: "cb" *not* output
Run Code Online (Sandbox Code Playgroud)
† Coliru的GCC安装有或没有-pedantic.