How to redefine a macro using its previous definition

送分小仙女□ 提交于 2019-12-08 19:03:59

问题


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


回答1:


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);
}

}



回答2:


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.




回答3:


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);



回答4:


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)



回答5:


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.



来源:https://stackoverflow.com/questions/3085071/how-to-redefine-a-macro-using-its-previous-definition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!