Concatenate string in C #include filename Concatenate string in C #include filename c c

Concatenate string in C #include filename


First I thought "that's easy", but it did take a few tries to figure out:

#define AA 10 #define BB 20#define stringify(x) #x#define FILE2(a, b) stringify(file_ ## a ## _ ## b)#define FILE(a, b) FILE2(a, b)#include FILE(AA, BB)

As requested I'll try to explain. FILE(AA, BB) expands to FILE2(AA, BB) but then AA and BB is expanded before FILE2, so the next expansion is FILE2(10, 20) which expands to stringify(file_10_20) which becomes the string.

If you skip FILE2 you'll end up with stringify(file_AA_BB) which won't work. The C standard actually spends several pages defining how macro expansion is done. In my experience the best way to think is "if there wasn't enough expansion, add another layer of define"

Only stringily will not work because the # is applied before AA is replaced by 10. That's how you usually want it actually, e.g.:

#define debugint(x) warnx(#x " = %d", x)debugint(AA);

will print

AA = 10


It is usually used like this:

#define stringify(x)  #x#define expand_and_stringify(x) stringify(x)#define AA 10#define BB 20#define TEXT1 "AA = " stringify(AA) " BB = " stringify(BB)#define TEXT2 "AA = " expand_and_stringify(AA) " BB = " expand_and_stringify(BB)TEXT1 = "AA = AA BB = BB"TEXT2 = "AA = 10 BB = 20"

It's called stringification. You should check this answer.