简体   繁体   English

C / C ++条件宏组合

[英]C/C++ conditional macros combining

Can I combine macros while writing code for C or C++? 在为C或C ++编写代码时,我可以组合宏吗? If not, why? 如果没有,为什么? If yes, how? 如果有,怎么样?

I'm interested on how to solve the following (not correct and NOT compiling!!!) idea: 我对如何解决以下问题感兴趣(不正确且不编译!!!)的想法:

#define FREE(x) if((x)) {                                         \
#ifdef MEM_DEBUG_                                                 \
    fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
#endif                                                             \
    free((x)); }

So, what I want to achieve is this: 所以,我想要实现的是:

I want to define the macro FREE in way that it will include an extra line if I have the MEM_DEBUG defined. 我想定义宏FREE ,如果我定义了MEM_DEBUG ,它将包含一个额外的行。

I know, that for solving this I can have two defines for the FREE based on MEM_DEBUG , like: 我知道,为了解决这个问题,我可以基于MEM_DEBUGFREE提供两个定义,例如:

#ifdef MEM_DEBUG
  #define FREE() something
#else 
  #define FREE() something else
#endif

but I'm just curios if there is another way! 但我只是好奇,如果有另一种方式!

Yes, you can define macros to encapsulate the idea of doing something when the flag is set. 是的,你可以定义宏来封装设置标志时做某事的想法。

#ifdef MEM_DEBUG
#   define IF_MEM_DEBUG( ... ) __VA_ARGS__
#   define IF_MEM_NDEBUG( ... )
#else
#   define IF_MEM_DEBUG( ... )
#   define IF_MEM_NDEBUG( ... ) __VA_ARGS__
#endif

#define FREE(x) \
if((x)) { \
    IF_MEM_DEBUG( \
        fprintf(stderr, "free:%p (%s:%d)\n", (x), __FILE__, __LINE__); \
    ) \
    free((x)); \
}

No, it's not possible to put preprocessing directives (lines starting with # ) inside a macro definition. 不,不可能在宏定义中放置预处理指令(以#开头的行)。 So the only thing you can do is the second method you mention - put the definitions inside the conditionals. 所以你唯一能做的就是你提到的第二种方法 - 将定义放在条件中。

Of course, if you're working on a bigger macro and only a part of it is #if -dependent, you can isolate the dependent part into a separate macro and use this in the bigger one, to keep the divergent definitions as small as possible. 当然,如果你正在处理一个更大的宏,并且只有一部分是#if -dependent,你可以将依赖部分隔离成一个单独的宏,并在较大的宏中使用它,以保持不同的定义尽可能小。可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM