[Developers] macro as macro argument

Erik Schnetter schnetter at cct.lsu.edu
Mon Mar 5 10:34:42 CST 2007


On Mar 5, 2007, at 10:06:49, David Rideout wrote:

> I have a C macro which employs internal variables, e.g.
>
> #define foo(arg1) { \
>   int internal_var; \
>   ... code(arg1) ... }
>
> Often the macro is invoked multiple times in a single source file,  
> which leads
> to a compiler warning about identical variables in scope or  
> something like
> this.  I tried a hack:
>
> #define foo(arg1, XX) { \
>   int internal_var##XX; \
>   ... code(arg1) ... }
>
> which I wanted to call with
>
> foo(bar, __LINE__)
>
> to give each internal variable a unique name, but this instead  
> makes each
> internal variable into 'internal_var__LINE__'.
>
> Can someone more familiar with the workings of the C preprocessor  
> suggest a
> way to avoid this compiler warning?

As shown, your code should not warn about identical variables in  
scope, since each macro closes its scope.  Do you have maybe other  
variables as well which have the same name?

Could you rewrite your code using inline functions, or maybe C++  
templates?  I often find this much cleaner than macros, and also much  
easier to debug.  You can use templates in C++ and have the remainder  
of your programme still in C style, if you prefer that.

If you want to continue with your existing approach, then the usual  
remedy is to add a bit of indirection by defining some additional  
macros with arguments.  See <http://www.decompile.com/cpp/faq/ 
file_and_line_error_string.htm> for an example; this doesn't do  
exactly what you want, but it handles __LINE__ and encounters a very  
similar error.

-erik

-- 
Erik Schnetter <schnetter at cct.lsu.edu>

My email is as private as my paper mail.  I therefore support encrypting
and signing email messages.  Get my PGP key from www.keyserver.net.



-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 186 bytes
Desc: This is a digitally signed message part
Url : http://www.cactuscode.org/pipermail/developers/attachments/20070305/8efce3aa/attachment.bin 


More information about the Developers mailing list