40

I would like to include a different file depending on the version of GCC. More precisely I want to write:

#if GCC_VERSION >= 4.2
#  include <unordered_map>
#  define EXT std
#elif GCC_VERSION >= 4
#  include <tr1/unordered_map>
#  define EXT std
#else
#  include <ext/hash_map>
#  define unordered_map __gnu_cxx::hash_map
#  define EXT __gnu_cxx
#endif

I don't care about gcc before 3.2.

I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
PierreBdR
  • 42,120
  • 10
  • 46
  • 62

3 Answers3

58

There are a number of macros that should be defined for your needs:

__GNUC__              // major
__GNUC_MINOR__        // minor
__GNUC_PATCHLEVEL__   // patch

The version format is major.minor.patch, e.g. 4.0.2

The documentation for these can be found here.

luke
  • 36,103
  • 8
  • 58
  • 81
33

Ok, after more searches, it one possible way of doing it is using __GNUC_PREREQ defined in features.h.

#ifdef __GNUC__
#  include <features.h>
#  if __GNUC_PREREQ(4,0)
//      If  gcc_version >= 4.0
#  elif __GNUC_PREREQ(3,2)
//       If gcc_version >= 3.2
#  else
//       Else
#  endif
#else
//    If not gcc
#endif
PierreBdR
  • 42,120
  • 10
  • 46
  • 62
  • 2
    Unfortunately this code fails with the clang compiler, which defines `__GNUC__`, but doesn't include `features.h`. – Gil May 22 '13 at 13:19
  • 1
    Well, this code is to know the version of GCC, so it's not surprising that it fails if clang partially impersonate GCC. – PierreBdR May 28 '13 at 11:44
  • 3
    Sorry, it seems I was wrong. The `features.h` include is simply a Linux specific thing, and should not be relied on for any code that is intended to compile on other platforms. – Gil May 29 '13 at 09:33
  • This code has been tested on Mac OS X, Windows (MingW32 and MingW64) and Linux ... I am fairly sure features.h is a GCC specific include file. – PierreBdR May 29 '13 at 10:19
  • 4
    The file is not directly from GCC, but rather from the glibc project. Surely, you can't assume the existence of this file based on the current compiler. – Gil May 29 '13 at 12:38
22

As a side note:

To find all the predefined macros:

  • Create empty file t.cpp
  • g++ -E -dM t.cpp
idmean
  • 14,540
  • 9
  • 54
  • 83
Martin York
  • 257,169
  • 86
  • 333
  • 562