How do I generate an error or warning in the C preprocessor?
C PreprocessorC Preprocessor Problem Overview
I have a program that must be compiled only in DEBUG mode. (testing purpose)
How can I have the preprocessor prevent compilation in RELEASE mode?
C Preprocessor Solutions
Solution 1 - C Preprocessor
Place anywhere:
#ifndef DEBUG
#error Only Debug builds are supported
#endif
Solution 2 - C Preprocessor
C provide a #error
statement, and most compilers add a #warning
statement. The gcc documentation recommends to quote the message.
Solution 3 - C Preprocessor
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 - C Preprocessor
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 - C Preprocessor
If you simply want to report an error:
#ifdef RELEASE
#error Release mode not allowed
#endif
will work with most compilers.
Solution 6 - C Preprocessor
For GCC and Clang (and probably any compiler that supports the _Pragma feature) you can define a macro:
#if ! DEBUG
#define FIX_FOR_RELEASE(statement) _Pragma ("GCC error \"Must be fixed for release version\"")
#else
#define FIX_FOR_RELEASE(statement) statement
#endif
You can use this macro for temporary hacks, for example to get around code that a co-worker hasn't written yet, to make sure you don't forget to fix it once you want to release a build to the public. Either
FIX_FOR_RELEASE()
// Code that must be removed or fixed before you can release
or
FIX_FOR_RELEASE(statement that must be removed or fixed before you can release);
Solution 7 - C Preprocessor
In Code::Blocks, if you don't want the Release mode, you can delete the Release mode. To do this, click on the Project menu, select Properties..., and in the Build targets tab you can click on Release and then click on the Delete button. Deleting the Release mode only does it for the current project, so you can still use it in other projects.
Otherwise, if you really want to use the preprocessor, you can do this:
#ifdef RELEASE
#error "You have to use the Debug mode"
#endif