2016-07-22 319 views
1

我正在编写一个程序,该程序在编译代码时需要编译器版本信息。在C++程序中输出编译器版本

为了简化问题,我的代码是一样的东西

#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main(int argc, char** argv) { 

    cout<<"The C++ compiler version is: "<<__STDC_VERSION__<<endl; 

    return 0; 
} 

一旦被编译并运行,它会输出我预计:

C++编译器的版本是:GCC 5.3.0

我试图编译它,并得到了一个错误:

​​

如何在我的代码中正确获取编译器版本?

+3

有没有标准化的方式来获得在不同的编译器的信息。 –

回答

2

我用这样的代码一次:

std::string true_cxx = 
#ifdef __clang__ 
    "clang++"; 
#else 
    "g++"; 
#endif 

    std::string true_cxx_ver = 
#ifdef __clang__ 
    ver_string(__clang_major__, __clang_minor__, __clang_patchlevel__); 
#else 
    ver_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); 
#endif 

其中ver_string定义:

std::string ver_string(int a, int b, int c) { 
    std::ostringstream ss; 
    ss << a << '.' << b << '.' << c; 
    return ss.str(); 
} 

还有另一个非常有用的宏(在gcc和铛)本:

__VERSION__ This macro expands to a string constant which describes the version of the compiler in use. You should not rely on its contents having any particular form, but it can be counted on to contain at least the release number.

gcc online docs

如果你需要处理MSVC和其他可能性,你将不得不检查他们使用的宏,我不记得他们手头。

+0

请注意'__VERSION__'由GCC定义,而不是任何标准。 –

+3

当然,你可以做得比使用函数返回一个字符串的代码如'#define STRINGIFY(x)#x'和 '#define VER_STRING(major,minor,patch)STRINGIFY(major)“更好。 STRINGIFY(次要)“。”字符串化(补丁)'。然后你可以使用'std :: string true_cxx_ver = VER_STRING(__ GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL __);'。 –

+0

是的,我同意,那好得多。我忘了你可以将数字串起来。 –

2

__STDC_VERSION__是C标准库的版本。它不是C++的一部分,也不是编译器的版本。

从GCC的文档:

This macro is not defined if the -traditional-cpp option is used, nor when compiling C++ or Objective-C.

这相当于是__cplusplus,它会告诉你的C++编译器所使用的标准版本。

编译器版本宏是供应商特定的,对于GCC他们__GNUC____GNUC_MINOR____GNUC_PATCHLEVEL__