user2826084
user2826084

Reputation: 545

Embedding preprocessor directive into function name

I want to embed a preprocessor directive into a function name. Basically I want to make a macro that takes a preprocessor define as argument and concatenates it's defined VALUE to get a function name.

Basically this:

#define PREFIX foo
#define CALL(P, x) _##P_bar(x)

...then 
CALL(PREFIX, x) should become _foo_bar(x)

Unfortunately this results in _P_bar instead of _foo_bar.

Is it possible to make it work as above?

Upvotes: 2

Views: 360

Answers (1)

Marian
Marian

Reputation: 7472

The C standard defines special behavior for macro parameters immediately preceded and followed by ## operator. In such case they are not fully expanded. This is why your code did not behave as you expected. To further expand a parameter, you have to use it in a way that it is not immediately preceded or followed by ## operator. Try the following:

#define PREFIX foo
#define CALL2(P,x) _##P##_bar(x)
#define CALL(P, x) CALL2(P,x)

CALL(PREFIX, x) 

Upvotes: 4

Related Questions