Search code examples
c++cc-preprocessor

Generating a preprocessor error if a define is used


Is it possible with the C++ preprocessor to emit an #error if a particular #define is used? Something like this:

#define this_must_not_be_used #error You shouldn't use that.

Solution

  • There is no standard way of defining a macro in such a way that its use, wherever it is, will give you a compilation error, especially not one that gives a clear and useful error message. For all you know, the code that uses it might just be stringizing its result, or it might be part of an assert condition that gets removed by the preprocessor.

    For most practical purposes, putting something that cannot possibly be part of a valid C (or C++) program will be good enough.

    Some implementations do have implementation-specific methods of achieving exactly what you ask for, though. For instance, with GCC, you can use

    #pragma GCC poison this_should_not_be_used
    

    where its subsequent use, no matter how it ends up used, will give:

    error: attempt to use poisoned "this_should_not_be_used"
    

    You may want to look at your own compiler's documentation to see if it has anything similar. You can also use conditional macro definitions, so that with GCC you use this approach, with your compiler you use your compiler's approach, and with an unknown compiler you fall back to the standard method of providing a macro definition that will probably lead to a difficult-to-read error message.