PDA

View Full Version : Preprocessor Macro Problem




Richard Birkett
Feb 26, 2012, 09:39 AM
I have a macro like this:

#define IntMethods(lower, cap, parameter) \
- (MMExpressionType)symboliccapWithInt:(SInt64)parameter\
{\
return [(MMExpressionType)self symboliccap:[[MMTerm alloc] initWithInteger:parameter]];\
}\
\
- (MMExpressionType)lowerWithInt:(SInt64)parameter\
{\
return [(MMExpressionType)self lower:[[MMTerm alloc] initWithInteger:parameter]];\
}

It is supposed to replace a repetitive set of implementations, I hope you understand what I am trying to do. My code here gets errors, it seems to think I'm literally using symboliccap etc. instead of something using the macro parameter.
Here is some desired output to input that will hopefully help if you don't understand.

IntMethods(add, Add, addend)
should be equivalent to
- (MMExpressionType)symbolicAddWithInt:(SInt64)exponent
{
return [(MMExpressionType)self symbolicAdd:[[MMTerm alloc] initWithInteger:addend]];
}

- (MMExpressionType)addWithInt:(SInt64)exponent
{
return [(MMExpressionType)self add:[[MMTerm alloc] initWithInteger:addend]];
}
Help greatly appreciated. :)



chown33
Feb 26, 2012, 10:09 AM
http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

Google search terms: c preprocessor token pasting

This is by far the most complex feature of the preprocessor, and it has some quirks. So I strongly recommend reading more than one reference, and looking at more than one example.

Richard Birkett
Feb 26, 2012, 10:38 AM
Thank you so much, that's perfect!
Here's my solution for reference:
#define IntMethods(lower, cap, parameter) \
- (MMExpressionType)symbolic##cap##WithInt:(SInt64)parameter\
{\
return [(MMExpressionType)self symbolic##cap:[[MMTerm alloc] initWithInteger:parameter]];\
}\
\
- (MMExpressionType)lower##WithInt:(SInt64)parameter\
{\
return [(MMExpressionType)self lower:[[MMTerm alloc] initWithInteger:parameter]];\
}

gnasher729
Feb 26, 2012, 10:39 AM
And when you get your macros working, you might consider whether you are not just trying to be too clever for your own good. Nothing more pleasant than looking for the definition of a method and not being able to find it anywhere in your source code. Or not being able to set a breakpoint in some method because of these macros.

Richard Birkett
Feb 26, 2012, 04:17 PM
And when you get your macros working, you might consider whether you are not just trying to be too clever for your own good. Nothing more pleasant than looking for the definition of a method and not being able to find it anywhere in your source code. Or not being able to set a breakpoint in some method because of these macros.

Well as you can see it is simple code really and they are all in the header anyway.