views:

104

answers:

4

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?

Thanks.

EDIT: according to this http://gcc.gnu.org/onlinedocs/gcc-3.3.6/cpp/Self_002dReferential-Macros.html it should be possible

A: 

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.

ereOn
Note that the `#ifdef` block is not needed. You can use `#undef` on a name to undefine it as a macro, even if that name isn't currently defined as a macro. So, you can simply `#undef xxx` and then `#define xxx...`.
James McNellis
@James McNellis: Good to know. Thanks!
ereOn
+5  A: 

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.

AProgrammer
+2  A: 

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);
Mike
Note that the `#ifdef` block is not needed. You can use `#undef` on a name to undefine it as a macro, even if that name isn't currently defined as a macro. So, you can simply `#undef xxx` and then `#define xxx...`.
James McNellis
Cool! Didn't know about that. Leaving off the `#ifdef` makes the code more readable.
Mike
+2  A: 

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

}
miquelramirez