X宏生成C风格字符串时意外含引号的解决求助
解决方案
问题出在你对#NAME的使用上——#NAME本身会将宏参数转换为字符串字面量(比如#REG1会生成"REG1"),而你额外添加的\""会让最终的字符串包含引号字符。只需移除这些多余的引号即可解决问题。
修改以下两处代码:
- 修正
rnames数组定义
原代码:
const char* const rnames[] = { #define X(NAME,VALUE) (const char* const) "\"" #NAME "\"", rinfo #undef X };
改为:
const char* const rnames[] = { #define X(NAME,VALUE) #NAME, rinfo #undef X };
(如果需要保留类型转换,可改为(const char* const) #NAME,,但这不是必须的)
- 修正
rmap的键值定义
原代码:
std::map<std::string, RNAME> rmap = { #define X(NAME,VALUE) { "\"" #NAME "\"", RNAME::RNAME_ ##NAME }, rinfo #undef X };
改为:
std::map<std::string, RNAME> rmap = { #define X(NAME,VALUE) { #NAME, RNAME::RNAME_ ##NAME }, rinfo #undef X };
完整修正后的代码
#include <map> #include <stdio.h> #define rinfo \ X( REG1, 10 ) \ X( REG2, 20 ) \ X( REG3, 33 ) \ enum class RNAME { #define X(NAME,VALUE) RNAME_ ## NAME = __COUNTER__, rinfo #undef X }; const char* const rnames[] = { #define X(NAME,VALUE) #NAME, rinfo #undef X }; std::map<std::string, RNAME> rmap = { #define X(NAME,VALUE) { #NAME, RNAME::RNAME_ ##NAME }, rinfo #undef X }; typedef struct { RNAME regname; const char* name; uint32_t value; }regx_t; regx_t regs[] = { #define X(NAME,VALUE) { RNAME::RNAME_ ## NAME, rnames[ (int)RNAME::RNAME_ ## NAME ], VALUE }, rinfo #undef X }; int main(int argc, char *argv[]){ int nErrors = 0; int n = sizeof(rnames) / sizeof(const char*); for (int i = 0; i < n; i++) { std::map<std::string, RNAME>::iterator it; it = rmap.find(rnames[i]); if (it != rmap.end()) { int index = (int)it->second; printf("rname[%d] = %s = %u = %s\r\n", i, rnames[i], regs[index].value, regs[index].name); } else { ++nErrors; } } printf("RNAME::RNAME_REG1 = %d\n", RNAME::RNAME_REG1); printf("RNAME::RNAME_REG2 = %d\n", RNAME::RNAME_REG2); printf("RNAME::RNAME_REG3 = %d\n", RNAME::RNAME_REG3); printf("%d errors found\n", nErrors); return 0; }
修改后的输出
rname[0] = REG1 = 10 = REG1 rname[1] = REG2 = 20 = REG2 rname[2] = REG3 = 33 = REG3 RNAME::RNAME_REG1 = 0 RNAME::RNAME_REG2 = 1 RNAME::RNAME_REG3 = 2 0 errors found
内容的提问来源于stack exchange,提问作者funbotix
相关产品推荐
相关产品推荐

