tags:

views:

114

answers:

4

Hello,

gcc 4.4.1

I am maintaining someone's code and I have come across something that I don't understand.

#define RES_API(name, func) name##_##func

Can anyone explain?

Many thanks,

+5  A: 

The ## is a concatenation operator. Using RES_API(name1, func1) in your code would be replaced with name1_func1. More information here.

Carl Norum
+1  A: 

Instead of doing OBJ_DoSomething, with this macro you can do RES_API(OBJ, DoSomething). Personally I think its silly.

popester
A huge amount of the preprocessor stuff is 'silly', until you suddenly find a reason why you can't do without it :)
KevinDTimm
+3  A: 

The ## operator concatenates two tokens. In your case, name is appended with an underscore, and that is appended with func.

So RES_API(aName, aFunc) results in aName_aFunc.

By itself, it seems rather annoying. I could see a use when mixing C and C++ code, as C libraries tend to prefix their functions, while C++ libraries would place them in a namespace.

Given an alternate definition, such as:

#define RES_API(name, func) name##::##func

You suddenly have a generic way to switch between a C interface, or C++.

GMan
Do you really need the token pasting operators in the C++ code? I would expect the compiler to object that '::' is not a valid identifier.
Jonathan Leffler
+3  A: 

I know you've already got your answer, but there is some great info on the C-FAQ which explains allot of the C Preprocessor magic.

Robert S. Barnes
Thanks that was a great link. There was some other stuff in there that I needed for some else like doing the varargs functions. Great.
robUK