Question

I have a macro DDLogDebug(...) and I would like to do the following

#define _DDLogDebug(arg...) DDLogDebug(args)
#undef DDLogDebug
#define DDLogDebug(args...) doSomething(); _DDLogDebug(arg...)

But it does not work. Instead of #define _DDLogDebug(arg...) DDLogDebug(args), I would need a command that "stores" the content of the macro DDLogDebug to _DDLogDebug.

  • Does something like that exist?

  • How should one do when one wants to modify a macro whose definition is not exposed?

Was it helpful?

Solution

You can't do something like this with the purely standard preprocessor.

The reason is that macro definition doesn't work like e.g. function definition in the main language: at the time when you define _DDLogDebug, it isn't actually linking to the definition of DDLogDebug - it's storing exactly what you wrote. It won't attempt to actually find an expansion for any names until the macro is being used in the program outside of any definitions. By that point, the definition for DDLogDebug is already gone.

This is actually a valuable and intended behaviour, because it allows the use of techniques like X-macros: one definition can provide a framework and let different calling contexts decide how to actually use it in different ways. Not only is the outer macro not dependent on definitions available at the time it was written, but meaning of its contents can change throughout the program without having to change its structure.

If you can't work around this problem, you might have some luck with the non-standard but widely-supported push_macro and pop_macro directives.


Example of the use of push and pop:

#define FOO 123
#pragma push_macro("FOO")
#undef FOO
FOO
#pragma pop_macro("FOO")
FOO

Run this through gcc -E and you'll see it emits FOO (newline) 123. Works with Clang.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top