2

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?

1
  • Note that names in global scope that start with an underscore are reserved for the compiler and library. You are not supposed to use these. Commented Dec 6, 2014 at 12:36

1 Answer 1

4

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure that #define CALL(P,x) _##P##_bar(x) doesn't works. I guess the issue was just identify P macro parameter becouse underscore hide it and the goal was do two concatenation and not just one.
@Micheled'Amico Yes. I've checked it. CALL(P,x) _##P##_bar(x) doesn't work.

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.