Write a macro for C/C++ #include

痞子三分冷 提交于 2019-12-10 17:16:50

问题


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:

  1. 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).
  2. Wrap the non-compliant libraries with your own header files.


来源:https://stackoverflow.com/questions/6813084/write-a-macro-for-c-c-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!