How do I generate an error or warning in the C preprocessor?

Solution 1:

Place anywhere:

#ifndef DEBUG
#error Only Debug builds are supported
#endif

Solution 2:

C provide a #error statement, and most compilers add a #warning statement. The gcc documentation recommends to quote the message.

Solution 3:

Maybe something more sofisticated, but it is only copy&paste of previous solutions. :-)

#ifdef DEBUG        
    #pragma message ( "Debug configuration - OK" )
#elif RELEASE   
    #error "Release configuration - WRONG"
#else
    #error "Unknown configuration - DEFINITELY WRONG"
#endif

P.S. There is also another way how to generate a warning. Create an unreferenced label like

HereIsMyWarning:

and don't reference it. During compilation, you will get a warning like

 1>..\Example.c(71) : warning C4102: 'HereIsMyWarning' : unreferenced label

Solution 4:

You can use a error directive for that. The following code will throw an error at compile time if DEBUG is not defined:

#ifndef DEBUG
#error This is an error message
#endif

Solution 5:

If you simply want to report an error:

#ifdef RELEASE
  #error Release mode not allowed
#endif

will work with most compilers.