Can I use a preprocessor variable in the #include directive?

This is what I am trying to do:

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

My main.cpp file:

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

This code is currently not compiling. How to fix it? And is this even possible?

+4
source share
3 answers

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

Instead of the -D solution, I would prefer to use the -I directive to specify include directories.

Given that 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 any other tool that you use) just specify the appropriate include directory , depending on whatever reason you want:

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

Important note: I do not know if you plan to use this as a debug / release switch. However, doing this would be strange: the interface (the included .h files) should not change between release and debug . If you ever need it, the usual way is to enable / disable parts of the code using definitions, mainly in .c (and .cpp ) files.

+8
source

You cannot do this directly, but it 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 comments below) .

Essentially, any #include statement that does not match the "normal" syntax (either #include "" or #include <> ) but has the form #include SOMETHING will result in SOMETHING preprocessing, after which it must match one of the "normal" syntaxes. SOMETHING can be any sequence of pp tokens.

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

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

... which does not match one of the "normal" syntaxes.

+4
source

I do not believe that this is described in the C ++ standard, so for a separate compiler provider it had to support it or not support it. I do not think so.

However, almost every compiler allows you to specify a search directory for headers. This is usually the / i option.

So this will be:

 $ c++ -i build/generated-content main.cpp My main.cpp file: #include "header.h" void f() { /* something */ } 
+1
source

Source: https://habr.com/ru/post/1315803/


All Articles