Why no warning with “#if X” when X undefined?

后端 未结 8 1144
孤独总比滥情好
孤独总比滥情好 2021-02-18 13:06

I occasionally write code something like this:

// file1.cpp
#define DO_THIS 1

#if DO_THIS
    // stuff
#endif

During the code development I ma

8条回答
  •  不要未来只要你来
    2021-02-18 13:19

    When you can't use a compiler that has a warning message (like -Wundef in gcc), I've found one somewhat useful way to generate compiler errors.

    You could of course always write:

    #ifndef DO_THIS
        error
    #endif
    #if DO_THIS
    

    But that is really annoying

    A slightly less annoying method is:

    #if (1/defined(DO_THIS) && DO_THIS)
    

    This will generate a divide by zero error if DO_THIS is undefined. This method is not ideal because the identifier is spelled out twice and a misspelling in the second would put us back where we started. It looks weird too. It seems like there should be a cleaner way to accomplish this, like:

    #define PREDEFINED(x) ((1/defined(x)) * x)
    #if PREDEFINED(DO_THIS)
    

    but that doesn't actually work.

提交回复
热议问题