开发者

Conditional macro #define for a function - causing: "function" redefined warning

I just saw this thread, describing how to add conditional macros: Conditional value for a #define

but in my case I am defining a function within the condition.

#if TARGET_IPHONE_SIMULATOR

#define doSomething(){\
    \\ does something
}\

#else

#define doSomething(){\
    \\ does something else
}\

#endif

This does work, except I is causing gcc compiler to throw this warning:

"doSomething" redefined
This is the location of the previous arguments

Is there any workaround to help getting rid of the warnings?

UPDATE:

So I tried including the condition inside my definition:

开发者_JAVA百科
#define doSomething(){\

#if TARGET_IPHONE_SIMULATOR
    \\ do something
#else 
    \\ do something else
#endif

}\

but that throws an error:

error: '#' is not followed by a macro parameter.


I found the answer to my question here.

Conclusion: you cannot include #ifdef etc... inside #define, because there should only be one pre-processing directive per line.

So although we can break the line with a backslash '\' this helps writing readable multiline macros, but the preprocessor will see it as one line:

#define doSomething(){ #if TARGET_IPHONE_SIMULATOR ... #endif }

Which throws this error:

error: '#' is not followed by a macro parameter.

That makes sense, so I will have to rethink my implementation.


There is a quirk in your thinking which is by analogy/ extension. doSomething() has to be viewed as a function-like macro. As such its definition is ambivalent. Zoom out and see below:

doSomething() {
#if TARGET_IPHONE_SIMULATOR
   // conditionally compiled code
#else
   // platform-specific code
#endif
}


Also, this might address the error you received:
# and ## have special purposes inside macro definitions. # is used to surround a macro parameter with double quotes. ## is used to concatenate two macro parameters. Example:
#define ABC(X) #X
ABC(hello) results in "hello".
#define XYZ(X,Y) X##Y
XYZ(O,K) results in OK. Note that this feature is (possibly) unique to ANSI C.
Also, why would you be using a macro like this? Might a function work better for you?


One option to consider is creating a condition in a macro that will resolve at compile time. Consider the following:

If I would like to call a different function based on the value of 'c' as a pre-processor action, I can define a macro that checks the value of 'c' statically.

#define AorB(c) ((c>0) ? (Do_A(c)) : (Do_B(c)))

Then if you configure a level of optimization that removes branches that are never reachable, it should strip out which ever case wasn't performed. This may not exactly be what you were looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜