Search code examples
cmacrosconditional-compilation

compare strings in ifdef directive


I pass a macto during compilation:

% gcc -DIDENT="abcd" app.c

What is the right way to check during compilation the macro? For example the following works, but throws warning:

#ifdef IDENT == "abcd"
printf("abcd\n");
#endif

warning: extra tokens at end of #ifdef directive.


Solution

  • #ifdef tests whether a symbol is defined, not what the value is, so is valid only as

    #ifdef SYMBOL
    

    #if expression will test whether an expression is true, however is limited to integers only.

    For more information, see the gcc preprocessor manual:

    https://gcc.gnu.org/onlinedocs/cpp/If.html

    https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html#Ifdef