Conditional macro expansion

后端 未结 3 1131
我在风中等你
我在风中等你 2021-01-12 13:31

Heads up: This is a weird question.

I\'ve got some really useful macros that I like to use to simplify some logging. For example I can do Log(@\"My message wi

相关标签:
3条回答
  • 2021-01-12 14:09

    You can use some sort of macro conditional:

    #ifndef OBJECTIVE_C
      #define self 0
      #define _cmd ""
    #endif
    

    I'm not quite sure what you should define self and _cmd to, those were just guesses.

    I'm not sure if there is a predefined macro that you can to check if you are compiling in Objective C so you may need to define OBJECTIVE_C manually as part of your build.

    0 讨论(0)
  • 2021-01-12 14:13

    You can use

    if defined "abc" <statement1>
    else if defined "def" <statement2>
    
    0 讨论(0)
  • 2021-01-12 14:22

    The preprocessor does all of its work before the actual code is parsed. The preprocessor cannot know whether a function is C or obj-C because it runs before the code is parsed.

    For the same reason,

    if (thisFunctionIsACFunction) {
      #define SELF nil
      #define CMD nil
    } else {
      #define SELF self
      #define CMD _cmd
    }
    DoLogging(SELF, CMD, format, ##__VA_ARGS__);
    

    cannot work - the #defines are processed before the compilation stage.

    So, the code itself must contain a "runtime" check (though the compiler may optimise this out).

    I would suggest defining something like

    void *self = nil; //not sure about the types that
    SEL _cmd = nil;   //would be valid for obj-c
    

    at global scope; the C functions will "see" these definitions while the Objective-C methods will hopefully hide them with their own definitions.

    0 讨论(0)
提交回复
热议问题