Paul Manta
Paul Manta

Reputation: 31597

Variable name from macro argument

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?

Upvotes: 34

Views: 53389

Answers (3)

Dmitri
Dmitri

Reputation: 9385

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)

Upvotes: 10

K-ballo
K-ballo

Reputation: 81399

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

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

Upvotes: 46

user142162
user142162

Reputation:

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

Upvotes: 4

Related Questions