32
votes

I'd like to do something like this:

class SomeClass { };

GENERATE_FUNTION(SomeClass)

The GENERATE_FUNCTION macro I'd like to define a function whose name is to be determined by the macro argument. In this case, I'd like it to define a function func_SomeClass. How can that be done?

3

3 Answers

41
votes
#define GENERATE_FUNCTION(Argument) void func_##Argument(){ ... }

More information here: http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation

10
votes

As everyone says, you can use token pasting to build the name in your macro, by placing ## where needed to join tokens together.

If the preprocessor supports variadic macros, you can include the return type and parameter list too:

#define GENERATE_FUNCTION(RET,NAM,...) RET func_##NAM(__VA_ARGS__)

..so, for example:

GENERATE_FUNCTION(int,SomeClass,int val)

..would expand to:

int func_SomeClass(int val)
4
votes
#define GENERATE_FUNCTION(class_name) func_##class_name##