Can I combine macros while writing code for C or 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.
I know, that for solving this I can have two defines for the FREE
based on MEM_DEBUG
, like:
#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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.