C#include filename中的连接字符串

ana*_*iaz 13 c macros concatenation include c-preprocessor

当#including文件名(在C中)时,是否可以从另一个宏连接字符串.例如,

我有,

#define AA 10 
#define BB 20
Run Code Online (Sandbox Code Playgroud)

这些是随程序运行而变化的参数

该文件包括:

#include "file_10_20" // this changes correspondingly i.e. file_AA_BB
Run Code Online (Sandbox Code Playgroud)

是否有可能以#include "file_AA_BB"某种方式?我用谷歌搜索发现双磅操作符可以连接字符串,但找不到这样做的方法.

任何帮助,将不胜感激.

Per*_*son 17

首先,我认为"这很容易",但确实需要花费一些时间才能弄明白:

#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)
Run Code Online (Sandbox Code Playgroud)

根据要求,我会试着解释一下.FILE(AA, BB)扩展到FILE2(AA, BB)后来AABBFILE2之前膨胀,所以接下来的膨胀FILE2(10, 20)而膨胀到stringify(file_10_20)成为该字符串.

如果你跳过FILE2,你最终stringify(file_AA_BB)将无法使用.C标准实际上花了几个页面来定义宏扩展是如何完成的.根据我的经验,最好的思考方式是"如果没有足够的扩展,添加另一层define"

只有字符串才会起作用,因为#在被替换为10之前应用#.这就是你通常想要它的方式,例如:

#define debugint(x) warnx(#x " = %d", x)
debugint(AA);
Run Code Online (Sandbox Code Playgroud)

将打印

AA = 10
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记 #undef FILE,因为它会与 <stdio.h> 中的某些内容发生冲突 (2认同)
  • @Per:谢谢你的解释.我想每个对这个问题感兴趣的人都会喜欢阅读http://www.delorie.com/gnu/docs/gcc/cpp_32.html (2认同)

Lih*_*ihO 5

它通常像这样使用:

#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"
Run Code Online (Sandbox Code Playgroud)

它被称为字符串化.你应该检查这个答案.