34

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?

0

3 Answers 3

46
#define GENERATE_FUNCTION(Argument) void func_##Argument(){ ... }

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

Sign up to request clarification or add additional context in comments.

4 Comments

Keep in mind if you give it a macro as a parameter, there's more preprocessor magic involved to make it work.
@Mooing Duck: Yes, an extra level of indirection to actually evaluate the Argument before pasting. However that does not seem to be the OP case.
What if I don't want the func_ part?
@qed If you don't want the func_ part to be there at all, you could just do #define GENERATE_FUNCTION(Argument) void Argument() { ... }
10

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)

Comments

4
#define GENERATE_FUNCTION(class_name) func_##class_name##

2 Comments

What does the final ## do?
Apparently makes it not work at all :) (GCC via mingw64)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.