How to use #if inside #define in the C preprocessor?

后端 未结 2 423
小鲜肉
小鲜肉 2020-11-27 20:13

I want to write a macro that spits out code based on the boolean value of its parameter. So say DEF_CONST(true) should be expanded into const, and

2条回答
  •  萌比男神i
    2020-11-27 20:36

    Doing it as a paramterised macro is a bit odd.

    Why not just do something like this:

    #ifdef USE_CONST
        #define MYCONST const
    #else
        #define MYCONST
    #endif
    

    Then you can write code like this:

    MYCONST int x = 1;
    MYCONST char* foo = "bar";
    

    and if you compile with USE_CONST defined (e.g. typically something -DUSE_CONST in the makefile or compiler options) then it will use the consts, otherwise it won't.

    Edit: Actually I see Vlad covered that option at the end of his answer, so +1 for him :)

提交回复
热议问题