Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

macros - Concatenate string in C #include filename

Is it possible to concatenate string from another macro when #including a file name (in C). For example,

I have,

#define AA 10 
#define BB 20

these are parameters that change with program runs

And the file include:

#include "file_10_20" // this changes correspondingly i.e. file_AA_BB

Is it possible to have something like #include "file_AA_BB" somehow? I googled to find that double pound operator can concat strings but couldn't find a way of doing it.

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...