Why compiler complain about this macro declaration

后端 未结 3 369
梦如初夏
梦如初夏 2021-01-01 23:30

I write the following macro for debug convinience,

1 #ifndef DEF_H
2 #define DEF_H
3 #define DEBUG_MODE
4 #define DEBUG_INFO(message)     \\
5         #ifdef         


        
相关标签:
3条回答
  • 2021-01-01 23:49

    You can't embed a preprocessor directive in another preprocessor directive (the #ifdef DEBUG_MODE inside the definition of DEBUG_INFO). Instead, do something like

    #ifdef DEBUG_MODE
    # define DEBUG_INFO(message) cout << message << endl
    #else
    # define DEBUG_INFO(message) 0
    #endif
    

    (This is still not ideal; defensive macro coding suggests something like

    #ifdef DEBUG_MODE
    # define DEBUG_INFO(message) do {cout << message << endl;} while (0)
    #else
    # define DEBUG_INFO(message) 0
    #endif
    

    Perhaps an inline function would work better.)

    0 讨论(0)
  • 2021-01-01 23:51

    You cannot have #ifdefs inside a macro definition. You need to turn it inside out:

    #ifdef DEBUG_MODE
    #define DEBUG_INFO(message) cout << (message) << endl
    #else
    #define DEBUG_INFO(message)
    #endif
    
    0 讨论(0)
  • 2021-01-02 00:04

    I geuss if you eat '\' at line 7, the piece of Code will work.

    0 讨论(0)
提交回复
热议问题