#error inside of #define - Possible in C++ (generate error WHEN calling macro MyMacro IF some constant is not defined)?

StackOverflow https://stackoverflow.com/questions/23320743

Question

I want to define the macro, that based on some condition (existence of #define INITED, not the parameter of the macro) will return value, or generate compiler's error, like:

#error Not initialized!

I've tried (for myIdea.h):

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #define MyMacro(x) #error Not initalized!
#endif

But that code generates error (not the one I wanted to) expected macro format parameter.

Note, that I don't want that code (working, but doing bit different thing):

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #error Not initalized!
#endif

The code above will geneate error just when INITED won't be defined. I want to generate error only when I call to the MyMacro() AND INITED has not been yet defined.

I'm not the slave to the first code, but I want the result to work exactly the way I've described above (generate error WHEN calling macro MyMacro IF constant inited is not defined).

Was it helpful?

Solution

This is not possible. The preprocessor is just a very simple thing, it does not parse nested macros like that. The second pound (#) would not be understood as a nested macro by the preprocessor. The argument is pretty much handled as raw string.

You could however look into static assert with C++11 and on instead of your #error directive. You would be writing then something like this:

#ifdef INITED
    #define MyMacro(x) x->method(); //something with x
#else
    #define MyMacro(x) static_assert(false, "Not initalized!");
#endif
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top