是否可以对已定义的常量使用# stringization ?

Is it possible to use # stringization with defined constants?

本文关键字:stringization 常量 定义 是否      更新时间:2023-10-16

我有一些字符串常量后面的部分由前面的组成

const char* ID       = "01099BB2";
const char* FS_LOCATION_ROOT =  "fs:/~0x";

我想创建的常量是串联,并尝试使用#,但得到编译错误:

const char* FS_LOCATION = FS_LOCATION_ROOT#ID;

是否有这样组合字符串的方法?

这取决于你想对这些字符串做什么。stringizer操作数#是预处理器的一部分,因此必须出现在宏定义中。但它似乎对你的特殊情况没有帮助。但是,您可以简单地使用连续字符串字面值被连接的事实。

"fs:/~0x" "01099BB2" is turned into "fs:/~0x01099BB2"

但是不能对变量使用,只能对字面量使用。你可以这样做:

#define ID "01099BB2"
#define FS_LOCATION_ROOT "fs:/~0x"
#define FS_LOCATION FS_LOCATION_ROOT ID

或者更好的

const char* FS_LOCATION = FS_LOCATION_ROOT ID

然而,在定义一个名为ID的宏之前,我会考虑两次。

一旦它们被定义为符号就不能。我想你可以同时生成这两个。

#define stupid_macro(ID,ROOT) 
  const char *id = #ID ; 
  const char *root = #ROOT ; 
  const char *both = #ID #ROOT ;

我没有测试它来验证stringize的工作,但它应该以这样结束。

const char *id = "id_val" ;
const char *root = "root_val" ;
const char *both = "id_val" "root_val" ;

最后一个将它们连接起来。这当然是合法的,但我不能说这是道德的。