C / C ++ Conditional Macro Combination

Is it possible to combine macros when writing code for C or C ++? If not, why? If so, how?

I am wondering 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, I want to achieve this:

I want to define a macro FREEso that it includes an extra line if I defined MEM_DEBUG.

I know that for this I can define two for FREEbased MEM_DEBUG, for example:

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

but I'm just curious if there is another way!

+4
source share
2 answers

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)); \
}
+4
source

, (, #). , , , , - .

, , #if -, , .

+2

All Articles