3

奇怪的是,以下 C++ 程序在 Sun Studio 10 上编译时不会对未定义的变量产生警告:

int main()
{
  return sun;
}

的值sun似乎是 1。这个变量是从哪里来的,它是干什么用的?

4

3 回答 3

4

它几乎可以肯定是一个预定义的宏。正式地,C 和 C++ 标准为此保留以下划线和大写字母开头或包含两个下划线的名称,但实际上,编译器在标准之前定义了此类符号,并继续支持它们,至少在它们的非兼容模式,这是我所知道的所有编译器的默认模式。我记得有一次 `linux' 有问题,但当我用 -std=c++89 调用 g++ 时没有。

于 2011-04-11T08:17:46.330 回答
2

它必须是编译器创建的自动宏之一。

尝试同样的事情,在 Linux 上替换sungnu使用 gcc 编译器。你会得到类似的结果。

使用 gcc,您可以使用以下命令获取所有预定义的宏:echo "" | gcc -E - -dM.

于 2011-04-11T07:42:59.770 回答
1

sun被定义为从采用下划线开始的公约之前的历史向后兼容性。对于 Studio,它记录在 cc(1) 和 CC(1) 手册页的 -D 标志下:

   -Dname[=def]

       Defines  a  macro  symbol  name  to  the preprocessor.  Doing so is
       equivalent to including a #define directive at the beginning of the
       source.  You can use multiple -D options.

       The following values are predefined.

       SPARC and x86 platforms:


         __ARRAYNEW
         __BUILTIN_VA_ARG_INCR
         __DATE__
         __FILE__
         __LINE__
         __STDC__ = 0
         __SUNPRO_CC = 0x5130
         __SUNPRO_CC_COMPAT = 5 or G
         __TIME__
         __cplusplus
         __has_attribute
         __sun
         __unix
         _BOOL if type bool is enabled (see "-features=[no%]bool")
         _WCHAR_T
         sun
         unix
         __SVR4 (Oracle Solaris)
         __SunOS_5_10  (Oracle Solaris)
         __SunOS_5_11  (Oracle Solaris)
...

各种标准合规选项可以禁用它,+pCC 的标志也可以。

于 2016-12-31T06:22:46.320 回答