用C#包括文件名字符串连接 [英] Concatenate string in C #include filename

查看:379
本文介绍了用C#包括文件名字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能(在C)#包括文件名时从另一个宏串连字符串。例如,

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

我有,

#define AA 10 
#define BB 20

这些都是与程序运行更改参数

these are parameters that change with program runs

和文件包括:

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

是否有可能有类似的#includefile_AA_BB不知何故?我用Google搜索,发现双一斤操作员可以Concat的字符串,但找不到这样做的一种方式。

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.

任何帮助将是AP preciated。

Any help would be appreciated.

推荐答案

首先,我想:这很容易,但它确实需要一些试图找出:

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)

根据要求,我会尽量解释。 FILE(AA,BB)扩展到 FILE2(AA,BB) AA BB 是FILE2前扩大,因此未来扩张 FILE2(10,20)它扩展成字符串化(file_10_20)变成字符串。

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.

如果你跳过FILE2你会字符串化(file_AA_BB)结束这是行不通的。 C标准实际上花费几页确定如何扩展宏完成的。以我的经验认为最好的办法就是:如果没有足够的扩展,增加了另一层定义

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"

只是由于应用了#替换AA之前stringily将无法正常工作10。这就是你平时是怎么想它实际的,例如:

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);

将打印

AA = 10

这篇关于用C#包括文件名字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆