Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 567
jackhab Avatar asked Jun 21 '10 13:06

jackhab


3 Answers

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];
like image 62
Александр Калюжный Avatar answered Oct 19 '22 16:10

Александр Калюжный


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);
like image 44
Mike Avatar answered Oct 19 '22 15:10

Mike


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)
like image 40
snv.dev Avatar answered Oct 19 '22 16:10

snv.dev