宏重新定义
Macro redefined
我试图让我的代码更具可读性,所以我定义了以下宏来缩短对嵌套结构中组件的访问。
#define _ENTRY(i) policy_data->entries[i]
#define _ENTRY(i,j) policy_data->entries[i].sub_entry[j]
尝试此操作时,我收到有关“_ENTRY”被重新定义的编译器警告。
我认为宏只是一种替换 C 文件中某些模板定义的字符串的复杂方法。
预处理器在编译前完成的工作。
那么为什么编译器会关心这个呢?
我怎样才能不出错地实现相同的功能?
使用像 _ENTRY
这样的标识符本身就是导致未定义行为的原因。
C11 标准针对 identifiers 规定了这一点:
7.1.3 Reserved identifiers
1 Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
...
3 If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.
所以有可能在某些实现中删除整个宏。这也进一步导致了可移植性问题。
C11 标准在 Annexure on Portability and Undefined behavior 中声明:
The program removes the definition of a macro whose name begins with an
underscore and either an uppercase letter or another underscore
我试图让我的代码更具可读性,所以我定义了以下宏来缩短对嵌套结构中组件的访问。
#define _ENTRY(i) policy_data->entries[i]
#define _ENTRY(i,j) policy_data->entries[i].sub_entry[j]
尝试此操作时,我收到有关“_ENTRY”被重新定义的编译器警告。
我认为宏只是一种替换 C 文件中某些模板定义的字符串的复杂方法。 预处理器在编译前完成的工作。
那么为什么编译器会关心这个呢? 我怎样才能不出错地实现相同的功能?
使用像 _ENTRY
这样的标识符本身就是导致未定义行为的原因。
C11 标准针对 identifiers 规定了这一点:
7.1.3 Reserved identifiers
1 Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.
- All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
...
3 If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.
所以有可能在某些实现中删除整个宏。这也进一步导致了可移植性问题。
C11 标准在 Annexure on Portability and Undefined behavior 中声明:
The program removes the definition of a macro whose name begins with an underscore and either an uppercase letter or another underscore