是否可以通过#define 将 g++ 设置为遵循 C++11 ISO (-std=c++11)?

Is it possible to set g++ to follow C++11 ISO (-std=c++11) through #define?

我对 c++11 很陌生,我想知道一些事情...

我正在使用 Code::Blocks,如果我要在此 IDE 中使用 c++11,我必须转到编译器设置,然后检查“Have g++ follow the C++11 ISO C++ language standard

是否有任何解决方法,以便我可以像这样在 #define 语句中设置单个 .cpp 文件以使用 c++11

注意:这是单个 "Build" 文件,不是项目

通过在不在项目中时设置编译选项,它会将其设置为我不想发生的全局编译选项

我知道您可以在项目文件中自定义构建选项,它将只为该项目设置c++11

#include <iostream>

#define -std c++11

int main(){

    #if __cplusplus==201402L
        std::cout << "C++14" << std::endl;
    #elif __cplusplus==201103L
        std::cout << "C++11" << std::endl;
    #else
        std::cout << "C++" << std::endl;
    #endif
    return 0;
}

我发现了什么:

更改 #define __cplusplus 201103L 不是一个好主意,因为它不会将编译器设置为编译为 c++11

Is it possible to set g++ to follow C++11 ISO (-std=c++11) through #define?

没有.

C++ 和 g++ 都没有这个特性。您可能希望手动构建简单的单文件程序。

没有.

您不应该更改 #define __cplusplus。在 How to trigger the __cplusplus (C++) #ifdef? 中阅读更多内容,因为 __cplusplus 应该由 C++ 编译器自动定义。这就是为什么要通过编译器设置更改版本。

例如,让一个文件遵循 C++11 而其他文件遵循 C++14 是没有意义的。整个工程应该是同构编译的。

请注意您的代码无法编译:Error: macro names must be identifiers using #ifdef 0

PS:如果您描述的是个好主意,那么在可读性和维护方面将是一场噩梦..

尽管我明白源文件在这方面如何自我记录是多么可取,但这是不可能的。

下一个最好的事情是测试一致性,正如您已经开始做的那样:

#if __cplusplus < 201103L
#error This source must be compiled as C++11 or later
#endif

这确保使用 C++03 编译器进行编译会立即给出简单易懂的错误消息。