I want to have a macro SomeMacro(city, country) in a file that will be in a file MacroFile.h that I will #include from either a .h file or a .m file. And I want SomeMacro to become something different depending on whether the file immediately above MacroFile.h in the include tree is a .h file or a .m file. I want to do this without defining a special constant in the .m file. Is that possible?
In pseudo-code, what I want MacroFile.h to do is this:
#if (file from which I was directly included is a .h)
#define SomeMacro(city, country) SomeStuffInvolvingCityAndCountry
#else
#define SomeMacro(city, co开发者_开发问答untry) SomeDifferentStuffInvolvingCityAndCountry
#endif
SomeMacro(washington, USA)
SomeMacro(tokyo, Japan)
SomeMacro(berlin, Germany)
Bonus points if you can also get MacroFile.h to examine what is two levels above it in the include tree.
EDIT: If there is a way for the macro to tell whether or not it is being called from inside an @implementation block, that would be good enough.
There is no preprocessor test to determine where the macro is being expanded from. .h
is a convention for a header file, but has no semantic value.
You could create two files MacroFile-header.h
and MacroFile-code.h
as follows:
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
Always import MacroFile-header.h
in your header files, as follows:
SomeObject.h:
#import "MacroFile-header.h"
// use macros
and MacroFile-code.h
after all other imports, in your implementation:
SomeObject.m:
#import "SomeObject.h"
#import ...
#import ...
// always include last
#import "MacroFile-code.h"
// use macros
精彩评论