How to redefine a macro using its previous definition
Suppose I have the following macro:
#define xxx(x) printf("%s\n",x);
Now in certain files I want to use an "enhanced" version开发者_开发问答 of this macro without changing its name. The new version explores the functionality of the original version and does some more work.
#define xxx(x) do { xxx(x); yyy(x); } while(0)
This of course gives me redefition warning but why I get 'xxx' was not declared in this scope? How should I define it properly?
EDIT: according to this http://gcc.gnu.org/onlinedocs/gcc-3.3.6/cpp/Self_002dReferential-Macros.html it should be possible
Not possible. Macros can use other macros but they are using the definition available at expand time, not definition time. And macros in C and C++ can't be recursive, so the xxx in your new macro isn't expanded and is considered as a function.
Self-referential macros do not work at all:
http://gcc.gnu.org/onlinedocs/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros
If you're working on C++ you can obtain the same results with template functions and namespaces:
template <typename T> void xxx( x ) {
printf( "%s\n", x );
}
namespace my_namespace {
template <typename T> void xxx( T x ) {
::xxx(x);
::yyy(x);
}
}
You won't be able to reuse the old definition of the macro, but you can undefine it and make the new definition. Hopefully it isn't too complicated to copy and paste.
#ifdef xxx
#undef xxx
#endif
#define xxx(x) printf("%s\n",x);
My recommendation is defining an xxx2
macro.
#define xxx2(x) do { xxx(x); yyy(x); } while(0);
If we know type of 'x' parameter in the 'xxx' macro, we can redefine macro by using it in a function and then define the 'xxx' macro as this function
Original definition for the 'xxx' macro:
#define xxx(x) printf("xxx %s\n",x);
In a certain file make enhanced version of the 'xxx' macro:
/* before redefining the "xxx" macro use it in function
* that will have enhanced version for "xxx"
*/
static inline void __body_xxx(const char *x)
{
xxx(x);
printf("enhanced version\n");
}
#undef xxx
#define xxx(x) __body_xxx(x)
From: https://gcc.gnu.org/onlinedocs/gcc/Push_002fPop-Macro-Pragmas.html
#define X 1
#pragma push_macro("X")
#undef X
#define X -1
#pragma pop_macro("X")
int x [X];
It is not exactly what you're asking for but it can help.
You can #undef
a macro prior to giving it a new definition.
Example:
#ifdef xxx
#undef xxx
#endif
#define xxx(x) whatever
I never heard of (or seen) a recursive macro though. I don't think it is possible.
精彩评论