【问题标题】:Xcode -- have a macro behave differently depending on whether it is included from a .h file or a .m file?Xcode——根据它是从 .h 文件还是 .m 文件中包含的宏,它的行为会有所不同吗?
【发布时间】:2011-06-28 22:33:20
【问题描述】:

我想在一个文件中有一个宏 SomeMacro(city, country),该宏将位于一个文件 MacroFile.h 中,我将从 .h 文件或 .m 文件中#include 。而且我希望 SomeMacro 变得不同,具体取决于包含树中 MacroFile.h 上方的文件是 .h 文件还是 .m 文件。我想这样做而不在 .m 文件中定义特殊常量。这可能吗?

在伪代码中,我希望 MacroFile.h 做的是:

#if (file from which I was directly included is a .h)
#define SomeMacro(city, country) SomeStuffInvolvingCityAndCountry
#else
#define SomeMacro(city, country) SomeDifferentStuffInvolvingCityAndCountry
#endif

SomeMacro(washington, USA)
SomeMacro(tokyo, Japan)
SomeMacro(berlin, Germany)

如果您还可以获得 MacroFile.h 来检查包含树中它上面两个级别的内容,则可以加分。

编辑:如果宏有办法判断它是否是从 @implementation 块内部调用的,那就足够了。

【问题讨论】:

  • 我不认为 C 预处理器可以让你这样做,我不认为 GNU 预处理器有一个扩展可以让你这样做。如果您告诉我们您的实际目标可能会有所帮助...
  • 同意我们需要更多地了解正在尝试完成的工作以提供适当的帮助,但除此之外,为什么不定义两个不同的 Macro.h 文件,每个文件都包含您想要的宏,并在其中包含适当的文件合适的地方?
  • 我想使用宏来定义 getter 和 setter 的标头和实现,我通过访问另一个对象来获取/设置属性。我发现自己经常做这种转发。为了抑制文件的扩散,如果我可以为每个类设置一组转发宏,而不是两组,那就更好了。
  • 我质疑这种方法。工作方式不同但看起来相同的代码是邪恶的。并且标题可能会在这里和那里不加思索地包含在内。
  • 不要自作聪明。尽可能清晰和富有表现力。

标签: iphone objective-c xcode gcc macros


【解决方案1】:

没有预处理器测试来确定宏的扩展位置。 .h 是头文件的约定,但没有语义值。

您可以创建两个文件MacroFile-header.hMacroFile-code.h,如下所示:

MacroFile-header.h

// definitions
#define CityCountryMacro(city, country)  SomeStuffInvolvingCityAndCountry
#define StateZipMacro(state, zip)        SomeStuffInvolvingStateAndZip

MacroFile-code.h

// undefine MacroFile-header.h macros
#if defined(CityCountryMacro)
    #undef CityCountryMacro
#endif
#if defined(StateZipMacro)
    #undef StateZipMacro
#endif

// definitions
#define CityCountryMacro(city, country)  OtherStuffInvolvingCityAndCountry
#define StateZipMacro(state, zip)        OtherStuffInvolvingStateAndZip

始终在头文件中导入MacroFile-header.h,如下所示:

SomeObject.h

#import "MacroFile-header.h"

// use macros

MacroFile-code.h 所有其他导入之后,在您的实施中:

SomeObject.m

#import "SomeObject.h"
#import ...
#import ...

// always include last
#import "MacroFile-code.h"

// use macros

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多