开发者

How can I #include a file whose name is built up from a macro?

On a cross-platform project, I want to #include a header file whose name contains the name of the platform. I have a #define macro for the platform.

So for example, for

#define PLATFORM win32

I want

#include "engine\win32\devices_win32.h"

while for

#define PLATFORM linux

I want

#include "engine\linux\devices_linux.h"

I'm going with R开发者_如何学编程ichard Pennington's answer, minus one line of code - it works for me!

#define PLATFORM Linux
#define xstr(x) #x
#define str(x) xstr(x)
#define sub(x) x
#include str(sub(engine/PLATFORM/devices_)PLATFORM.h)


Usually, you would do something more like:

#ifdef WIN32
#include "devices_win32.h"
#endif
#ifdef LINUX
#include "devices_linux.h"
#endif

...rather than having a single PLATFORM definition which can be set differently depending on the platform.


#define PLATFORM Linux
#define xstr(x) #x
#define str(x) xstr(x)
#define sub(x) x
#define FILE str(sub(engine/PLATFORM/devices_)PLATFORM.h)

#include FILE

I'm not sure I'd use it, though. ;-) I had to use Linux rather than linux because linux is defined as 1 in my compiler.


Well in practice, this could be achieved using something like

#define PLATFORM win32

#define INCLUDE_FILE devices_ ## PLATFORM

#define QUOTED_INCLUDE_FILE #INCLUDE_FILE

#include QUOTED_INCLUDE_FILE

but the the following rule would prevent you from doing this:

C comments and predefined macro names are not recognized inside a #include' directive in which the file name is delimited with <' and `>'.

C comments and predefined macro names are never recognized within a character or string constant. (Strictly speaking, this is the rule, not an exception, but it is worth noting here anyway.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜