include文件名中连接字符串

include文件名中连接字符串

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

问题描述

#include 文件名(在 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

是否有可能以某种方式拥有类似 #include "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.

任何帮助将不胜感激.

推荐答案

一开始我以为这很容易",但确实花了一些时间才弄明白:

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) 但随后 AABB 在之前扩展FILE2,所以下一个扩展是 FILE2(10, 20) 扩展为 stringify(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,你最终会得到 stringify(file_AA_BB) 这不起作用.C 标准实际上用了好几页来定义宏扩展是如何完成的.以我的经验,最好的思考方式是如果没有足够的扩展,添加另一层 define"

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"

只有 stringily 不起作用,因为 # 在 AA 被 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#include文件名中连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:56