Output Compiler Version in a C++ Program

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.


If for some reason we are using the Boost library in our project, we can use macros that are defined in #include <boost/config.hpp>.

The following code:

std::string get_compile_version()
{
     char buffer[sizeof(BOOST_PLATFORM) + sizeof(BOOST_COMPILER) +sizeof(__DATE__ )+ 5];
     sprintf(buffer, "[%s/%s](%s)", BOOST_PLATFORM, BOOST_COMPILER, __DATE__);
     std::string compileinfo(buffer);
     return compileinfo;
}

to std::cout prints the following on my machine:

[Win32/Microsoft Visual C++ version 14.1](May 10 2019)

Other related macros are listed here.

Tags:

C++

Gcc