Search code examples
gccvisual-c++user-warning

user warnings on msvc AND gcc?


In MSVC I have this in a header:

#define STR(x)          #x
#define STR2(x)         STR(x)
#define NOTE(text)      message (__FILE__ "(" STR2(__LINE__) ") : -NOTE- " #text)
#define noteMacro(text) message (__FILE__ "(" STR2(__LINE__) ") : " STR2(text))

and I do

#pragma NOTE(my warning here)

GCC has:

#warning(my warning here)

However MSVC (2003) throws a fit when it sees #warning and gives "fatal error C1021: invalid preprocessor command 'warning'"

What can I do about this? Is there a way to have GCC recognize MSVC warnings or MSVC not throw an error on GCC warnings? Is there something I can do that works on both? I can have GCC warn me about unknown pragmas but that's not the most ideal solution.


Solution

  • The best solution I've found for this problem is to have the following in a common header:

    // compiler_warning.h
    #define STRINGISE_IMPL(x) #x
    #define STRINGISE(x) STRINGISE_IMPL(x)
    
    // Use: #pragma message WARN("My message")
    #if _MSC_VER
    #   define FILE_LINE_LINK __FILE__ "(" STRINGISE(__LINE__) ") : "
    #   define WARN(exp) (FILE_LINE_LINK "WARNING: " exp)
    #else//__GNUC__ - may need other defines for different compilers
    #   define WARN(exp) ("WARNING: " exp)
    #endif
    

    Then use

    #pragma message WARN("your warning message here")
    

    throughout the code instead of #warning

    Under MSVC you'll get a message like this:

    c:\programming\some_file.cpp(3) : WARNING: your warning message here
    

    Under gcc you'll get:

    c:\programming\some_file.cpp:25: note: #pragma message: WARNING: your warning message here
    

    Not perfect, but a reasonable compromise.