Issue
I am writing a program which needs the information of compiler version as the code is compiled.
To simplify the problem, my code is something like
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
cout<<"The C++ compiler version is: "<<__STDC_VERSION__<<endl;
return 0;
}
I would expected once it is compiled and it runs, it would output:
The C++ compiler version is: gcc 5.3.0
I tried to compile it, and got an error:
$ g++ main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:24:11: error: ‘__STDC_VERSION__’ was not declared in this scope
cout<<__STDC_VERSION__<<endl;
^
How to correctly get the compiler version in my code?
Solution
I used code like this once:
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
where ver_string
was defined:
std::string ver_string(int a, int b, int c) {
std::ostringstream ss;
ss << a << '.' << b << '.' << c;
return ss.str();
}
There's also another useful macro (on gcc and clang) for this:
__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.
See gcc online docs.
If you need to handle MSVC and other possibilities, you will have to check the macros that they use, I don't remember them off-hand.
Answered By - Chris Beck