Search code examples
gccxcode4macrosllvmconditional-compilation

Determine LLVM versus GCC at compile time


I'm trying to write a macro similar to the following:

#ifndef DEPRECATED_ATTRIBUTE_MESSAGE
  #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated (message)))
#endif

And this works, but only with the Apple LLVM 3.0 compiler. It breaks at compile time for anything else meaning I have to strip it down to

#ifndef DEPRECATED_ATTRIBUTE_MESSAGE
  #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated))
#endif

which is much less useful.

My question:

I think the solution is to apply some macro to identify the version of the compiler at compile time. Is there a way to identify the Apple LLVM 3.0 compiler versus LLVM GCC 4.2 or GCC 4.2 (or anything else)?

Ideally, I'd like to work out something like this, but I can't find the right macro to figure it out:

#ifdef [Apple LLVM 3.0]
  #ifndef DEPRECATED_ATTRIBUTE_MESSAGE
    #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated (message)))
  #endif
#else
  #ifndef DEPRECATED_ATTRIBUTE_MESSAGE
    #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated))
  #endif
#endif

Solution

  • It should work with Clang’s feature checking macros:

    // In case the compiler/preprocessor doesn't support __has_extension
    #ifndef __has_feature         // Optional of course.
      #define __has_feature(x) 0  // Compatibility with non-clang compilers.
    #endif
    #ifndef __has_extension
      #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
    #endif    
    
    #if __has_extension(attribute_deprecated_with_message)
      #ifndef DEPRECATED_ATTRIBUTE_MESSAGE
        #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated (message)))
      #endif
    #else
      #ifndef DEPRECATED_ATTRIBUTE_MESSAGE
        #define DEPRECATED_ATTRIBUTE_MESSAGE(message) __attribute__((deprecated))
      #endif
    #endif