Xcode - 根据宏是否包含在.h文件或.m文件中,宏的行为会有所不同?

时间:2011-06-28 22:33:21

标签: iphone objective-c xcode gcc macros

我希望在一个文件MacroFile.h中有一个宏SomeMacro(city,country),我将从.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块中调用的,那就足够了。

1 个答案:

答案 0 :(得分:0)

没有预处理器测试来确定宏的扩展位置。 .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
相关问题