ant2009
ant2009

Reputation: 22696

#define statement explained

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,

Upvotes: 3

Views: 519

Answers (4)

Robert S. Barnes
Robert S. Barnes

Reputation: 40588

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.

Upvotes: 4

GManNickG
GManNickG

Reputation: 504323

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++.

Upvotes: 4

popester
popester

Reputation: 1934

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

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 225262

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

Upvotes: 6

Related Questions