问题
I work on AS/400 which is sometimes non-POSIX. We also need to compile our code on UNIX. We have an issue with something as simple as #include.
On AS/400, we need to write:
#include "*LIBL/H/MYLIB"
On UNIX, we need to write
#include "MYLIB.H"
At the moment we have this (ugly) block at the top of each C/C++ file:
#ifndef IS_AS400 #include "*LIBL/H/MYLIB" /* others here */ #else #include "MYLIB.H" /* others here */ #endif
We would like a unified macro. Is this possible? I don't know how to write it.
Ideally, the resulting syntax would be:
SAFE_INCLUDE("MYLIB")that would expand correctly on each platform.
Please advise.
回答1:
You can simply #include
some separate header in every of your source files containing that ugly #ifndef
just once. It's a common practice anyway.
回答2:
You can define prefixes for your platform as macro. Like
#define STRINGY(STR) #STR
#define SAFE_INCLUDE(HDR) STRINGY(HDR)
#ifndef IS_AS400
#define SAFE_INCLUDE(LIB) STRINGY(*LIBL/H/##LIB)
#else
#define SAFE_INCLUDE(LIB) STRINGY(LIB##.H)
#endif
and you can use this as
#include SAFE_INCLUDE(MYLIB)
回答3:
There are two better solutions:
- Use your Makefiles to properly set a path where compiler looks for includes.
For GCC you add to CFLAGS
-I <path>
(you can do that multiple times). - Wrap the non-compliant libraries with your own header files.
来源:https://stackoverflow.com/questions/6813084/write-a-macro-for-c-c-include