gpt4 book ai didi

c++ - 在 gcc 中将未保留的标识符作为内置宏的原因是什么?

转载 作者:IT老高 更新时间:2023-10-28 12:58:12 29 4
gpt4 key购买 nike

今天我偶然发现了一个相当有趣的编译器错误:

int main() {
int const unix = 0; // error-line
return unix;
}

在 gcc 4.3.2 中给出以下信息(是的,古老的...):

error: expected unqualified-id before numeric constant

这绝对是相当令人困惑的。

幸运的是,clang (3.0) 更有帮助(和往常一样):

error: expected unqualified-id
int const unix = 0
^
<built-in>:127:14: note: expanded from:
#define unix 1
^

我当然没想到unix既不是大写也不是下划线开头的宏,尤其是内置宏。

我检查了 gcc 中的预定义宏,有 2 个(在我的平台上)使用“未保留”符号:

$ g++ -E -dM - < /dev/null | grep -v _
#define unix 1
#define linux 1

所有其他都是带有前导下划线的“行为良好”的宏,使用传统的保留标识符,示例:

#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1

#define __unix__ 1
#define __unix 1

#define __CHAR_BIT__ 8
#define __x86_64 1
#define __amd64 1
#define _LP64 1

(乱七八糟,好像没有什么特别的顺序……)

此外,还有很多“相似”的符号,所以我想存在向后兼容性的问题......

那么,unixlinux 宏从何而来?

最佳答案

gcc 默认不完全符合任何 C 标准。

使用 -ansi-std=c99-std=c1x 调用它,并且 unix 获胜'不是预定义的。 (在 future 最近的 gcc 版本中,-std=c1x 可能会变成 变成 -std=c11。)

这有点令人困惑,这是在单独的 GNU 预处理器手册中记录的,而不是在 gcc 手册中。

引用 GNU 预处理器文档(info cpp,4.5 版):

The C standard requires that all system-specific macros be part of the "reserved namespace". All names which begin with two underscores, or an underscore and a capital letter, are reserved for the compiler and library to use as they wish. However, historically system-specific macros have had names with no special prefix; for instance, it is common to find `unix' defined on Unix systems. For all such macros, GCC provides a parallel macro with two underscores added at the beginning and the end. If `unix' is defined, `__unix__' will be defined too. There will never be more than two underscores; the parallel of `_mips' is `__mips__'.

When the `-ansi' option, or any `-std' option that requests strict conformance, is given to the compiler, all the system-specific predefined macros outside the reserved namespace are suppressed. The parallel macros, inside the reserved namespace, remain defined.

We are slowly phasing out all predefined macros which are outside the reserved namespace. You should never use them in new programs, and we encourage you to correct older code to use the parallel macros whenever you find it. We don't recommend you use the system-specific macros that are in the reserved namespace, either. It is better in the long run to check specifically for features you need, using a tool such as `autoconf'.

手册的当前版本是here .

关于c++ - 在 gcc 中将未保留的标识符作为内置宏的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8677390/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com