为什么我不能定义这些宏名称?

时间:2014-10-07 09:09:28

标签: c++

如果我对-Dfirst-Dsecond这样的命令进行定义,我会收到一堆错误:

In file included from main.cpp:1:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/iostream:39:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/ostream:38:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/ios:40:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/char_traits.h:39:
In file included from /usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_algobase.h:64:
/usr/local/bin/../lib/gcc/x86_64-unknown-linux-gnu/4.9.0/../../../../include/c++/4.9.0/bits/stl_pair.h:101:11: error: expected member name or ';' after declaration specifiers
      _T1 first;                 /// @c first is a copy of the first object
      ~~~ ^
<command line>:1:15: note: expanded from here
#define first 1
              ^
...
              ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.

但是,如果我使用大写FIRSTSECOND就可以了。

2 个答案:

答案 0 :(得分:7)

如果您在包含std::pair <algorithm>之内的任何内容之前定义第一个和第二个,那么它将会破坏您的代码,因为std::pair中的变量称为first并且second,并且您的宏被定义为,因此它将名称扩展为它们定义的表达式,从而使您的代码格式错误。

基本上,它和做

一样
#define A 1

class A{
};

这也不会编译,因为A转换为1,而1不是有效的类名

答案 1 :(得分:1)

正如您所看到的,第一个和第二个在整个STL中使用,因此通过将它们定义为无,您已将其渲染为不可解析