c++ – How to collect include from define


How from

#define filename myfilename
#define path ../driver/

go to


which after preprocessing will go to

#include "../driver/myfilename.h"

I have already spent a lot of time on various combinations of ##, but I never came to what I needed. I would continue to experiment if the result was clearly visible.


#define path ../driver/

And who will put the quotes?


There are two defines that define the path in the condition.

Understood. Here's a working sequence of steps:

The final version of the code:

#define STD std 
#define IOH io.h

#define STR(x) #x
#define JOIN(x,y) STR(x##y)
#define INC(x,y) JOIN(x,y)

#include INC(STD,IOH)

int main(void)
return !printf("YES");

Why is that?

  1. The concatenation of "таких" "строк" is done later. Include must not contain this. Therefore, expanding the argument to a string (single argument) should be done in the last step. STR does this.

  2. To pass arguments to STR they must be concatenated – this is done by JOIN .

  3. Since include passes what define itself, if you call JOIN right away, then the names of the definitions will be combined, not the values. We add one more level so that they unfold – this is INC .

That's all, it works.

And now we change std and io.h to the vehicle data, run it in gcc and get a bunch of swearing

Checked: http://codepad.org/WY0TkYMS

Line 0: error: pasting "/" and "myfilename" does not give a valid preprocessing token
Line 27: error: ../driver/myfilename: No such file or directory

Perhaps you can do something about this with compilation switches. Because there is some kind of vague error about the slash, but further in the 27th line an attempt is made to connect a file with a well-formed name (of course, it is not on the codepad).

Unfortunately, I am not an expert on gcc compilation keys. Perhaps someone can suggest how to fix this problem.

How about using a fictitious directory to climb up from?
Thanks avp for the idea.

#define filename _/../myfilename
#define path ../driver/_

#define STR(x) #x
#define JOIN(x,y) STR(x##y)
#define INC(x,y) JOIN(x,y)

#include INC(path,filename)

int main(void)
return !printf("YES");
Scroll to Top