开发者

Can I use a preprocessor variable in #include directive?

This is what I'm trying to do:

$ c++ -D GENERATED=build/generated-content main.cpp

My main.cpp file:

#include "GENERATED/header.h"
void f() { /* somethi开发者_开发问答ng */ }

Currently this code fails to compile. How should I fix it? And whether it's possible at all?


It seems you want to use different headers depending on some "compilation profile".

Instead of the -Dsolution, I would rather suggest using the -I directive to specify the include directories.

Given you have the following file tree:

/
  debug/
    header.h
  release/
    header.h

main.cpp:

#include "header.h"

/* some instructions, not relevant here */

And in your Makefile (or whatever tool you use), just specify the proper include directory to use, depending on whatever reason you want:

g++ -I debug main.cpp // Debug mode

g++ -I release main.cpp // Release mode

Important foot note: I don't know if you intended to use this as a debug/release switch. However, doing so would be weird: the interface (the included .h files) shouldn't change between release and debug. If you ever need this, the usual way is to enable/disable some parts of the code using defines, mostly in .c (and .cpp) files.


You can't do that directly, but this is possible:

c++ -D "GENERATED=\"build/generated-content\"" main.cpp  

#define INCLUDE_NAME() GENERATED "/header.h"
#include INCLUDE_NAME()

EDIT: This solution does not work (see the comments below).

Essentially, any #include statement not conforming to the 'normal' syntax (either #include "" or #include <>) but being of the form #include SOMETHING will cause SOMETHING to be preprocessed, after which it has to conform to one of the 'normal' syntaxes. SOMETHING can be any sequence of pp-tokens.

However in this case, the result (as generated by GCC) is...

#include "build/generated-content" "/header.h"

... which does not conform to one of the 'normal' syntaxes.


I don't believe that is covered in the C++ Standard, so it would be up to the individual compiler vender whether or not to support it. I don't think any do.

However, just about every compiler allows you to specify a search directory for headers. It's usually the /i option.

So it would be:

$ c++ -i build/generated-content main.cpp 
My main.cpp file:

#include "header.h" 
void f() { /* something */ } 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜