tags:

views:

87

answers:

3

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() { /* something */ }

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

+1  A: 

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: 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.

hkaiser
Looks like a trick though...
Pmod
That is crazy and gives me very evil ideas. Is it standard? Hard to Google for.
integer
Yep, that's standard (clause [16.2.4]). I edited my answer accordingly.
hkaiser
@int: See [this question](http://stackoverflow.com/questions/1736654/macros-as-arguments-to-preprocessor-directives).
Georg Fritzsche
hkaiser, using GCC this results in `#include "build/generated-content" "/header.h"` which doesn't work.
Georg Fritzsche
Ooops, you're right. As I wrote above, after preprocessing it has to conform to one of the 'normal' syntaxes... And string concatenation happens after preprocessing. I'll think about an alternative solution.
hkaiser
A: 

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 */ } 
James Curran
+7  A: 

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.

ereOn
+1 for the important footnote!
Justin Ardini