C++11:MinGW当指定-std=c++11选项时 默认定义了__STRICT_ANSI__

时间:2022-06-22
本文章向大家介绍C++11:MinGW当指定-std=c++11选项时 默认定义了__STRICT_ANSI__,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/51105863

__STRICT_ANSI__的来历

__STRICT_ANSI__是gcc编译器的的一个预定义宏,一般来说当使用了-ansi编译选项,就会定义这个宏。 关于__STRICT_ANSI__的来历,参见下面关于gcc编译选项的说明:

-ansi 支持符合ANSI标准的C程序. 这样就会关闭GNU C中某些不兼容ANSI C的特性,例如asm, inline和 typeof关键字,以及诸如unix和vax这些表明当前系统类型的预定义宏.同时开启 不受欢迎和极少使用的ANSI trigraph特性,以及禁止$成为标识符的一部分. 尽管使用了-ansi选项,下面这些可选的关键字, __asm__, __extension__, __inline____typeof__仍然有效.你当然不会把 他们用在ANSI C程序中,但可以把他们放在头文件里,因为编译包含这些头文件的程序时,可能会指定 -ansi选项.另外一些预定义宏,如__unix____vax__,无论有没有使用 -ansi选项,始终有效. 使用-ansi选项不会自动拒绝编译非ANSI程序,除非增加-pedantic选项作为 -ansi选项的补充. 使用-ansi选项的时候,预处理器会预定义一个__STRICT_ANSI__宏.有些头文件关注此宏,以避免声明某些函数,或者避免定义某些宏,这些函数和宏不被ANSI标准调用;这样就不会干扰在其他地方 使用这些名字的程序了. 摘自:http://www.cnblogs.com/liangxiaxu/articles/2617367.html 英文原文参见这里:https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/C-Dialect-Options.html#C-Dialect-Options

按照上面这些说明,我们可以理解为,编译器定义是否__STRICT_ANSI__取决于我们在编译代码时,是否使用了-ansi选项。如果没有指定-ansi,就不会有__STRICT_ANSI__

-std=c++11下的变化

但是到gcc全面支持C++11以后,这个逻辑好像就不对了。 下面是一段测试代码。

#include <iostream>
using namespace std;
#ifdef __STRICT_ANSI__
string ansi_status="__STRICT_ANSI__ defined";
#else
string ansi_status="__STRICT_ANSI__ undefined";
#endif
int main() {
    cout << ansi_status << endl; 
    return 0;
}

在MinGW下,不指定-std=c++11时,编译

16:15:37 * Incremental Build of configuration Debug for project strict_ansi_test * Info: Internal Builder is used for build g++ -O0 -g3 -Wall -c -fmessage-length=0 -o “srcstrict_ansi_test.o” “..srcstrict_ansi_test.cpp” g++ -o strict_ansi_test.exe “srcstrict_ansi_test.o” 16:15:39 Build Finished (took 1s.954ms)

运行结果为:

__STRICT_ANSI__ undefined

指定-std=c++11时,编译

16:19:52 **** Incremental Build of configuration Debug for project strict_ansi_test ****
Info: Internal Builder is used for build
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -o "src\strict_ansi_test.o" "..\src\strict_ansi_test.cpp" 
g++ -o strict_ansi_test.exe "src\strict_ansi_test.o" 
16:19:53 Build Finished (took 1s.433ms)

运行结果为:

__STRICT_ANSI__ defined

总结

以上测试总结下来,就是当指定MingW支持C++11时,不论编译是否使用-ansi选项,默认就定义了__STRICT_ANSI__。 这是有意为之还是一个bug现在不能确定,但这个变化是需要注意。 linux平台下的gcc是否也是这样,还没有测试。

如果要在-std=c++11选项时不允许编译器预定义__STRICT_ANSI__,就在编译选项中指定 -U__STRICT_ANSI__

16:32:13 * Incremental Build of configuration Debug for project strict_ansi_test * Info: Internal Builder is used for build g++ -std=c++0x -U__STRICT_ANSI__ -O0 -g3 -Wall -c -fmessage-length=0 -o “srcstrict_ansi_test.o” “..srcstrict_ansi_test.cpp” g++ -o strict_ansi_test.exe “srcstrict_ansi_test.o” 16:32:14 Build Finished (took 1s.240ms)

运行结果

__STRICT_ANSI__ undefined

本文使用的MinGW编译器版本为5.2.0 参考:http://stackoverflow.com/questions/5580921/how-can-i-make-c0x-and-strict-ansi-get-along