6

given the following code:

void doSomething(int one, int two, int three)
{
   //something here
}

#define ONE 1,2,3

#define TWO(arg) doSomething(arg);

#define THREE(arg) TWO(arg)

void doSomethingElse()
{
   TWO(ONE)

   THREE(ONE)
}

visual studio 2010 has the following preprocessor output (omitting some blank lines):

void doSomething(int one, int two, int three)
{

}    

void doSomethingElse()
{
   doSomething(1,2,3);

   doSomething(1,2,3);    
}

while gcc 4.2 gives the following:

void doSomething(int one, int two, int three)
{

}    

void doSomethingElse()
{
   doSomething(1,2,3);

myFile.cpp:17:13: error: macro "TWO" passed 3 arguments, but takes just 1 
   TWO
}

I'm not sure which is standard, but I'd like it to work like visual studio is working. Is there a way to refactor the code so that it works this way in both compilers?

3
  • 1
    Usually when VS and gcc differ, it's gcc that's correct. Oct 18 '12 at 21:55
  • This is a known bug in the Visual C++ preprocessor: it does not expand macros prior to rescanning. gcc's behavior is correct. Oct 18 '12 at 22:31
  • Thanks for all the responses...in terms of the solutions presented, I think I simplified my example too much and couldn't get them to work. I found another workaround but it's not illustrative to this general issue so I'll omit it here.
    – user109078
    Oct 19 '12 at 0:32
3

Another possibility would be parenthesizing the argument so that it doesn't become 3 arguments in the substitution:

#define ONE 1,2,3                                                                                                                                                                                                                                                              
#define TWO_PARENS(arg) doSomething arg;                                                                                                                                                                                                                                       
#define TWO(arg) TWO_PARENS((arg));                                                                                                                                                                                                                                           
#define THREE(arg) TWO_PARENS((arg))
THREE(ONE)          

BTW gcc is right according to the spec.

1

Commas need special handling when you're using them within another macro.

This should work:

#define ONE() 1,2,3
#define TWO(ARG) doSomething(ARG());
#define THR(ARG) TWO(ARG)

You delay ONE being replaced immediately by turning it into function like macro itself.

You can see more examples of avoiding this with BOOST_PP_COMMA_IF on the boost documentation site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.