读书人

一个用带参宏定义字符串的语法,该怎么

发布时间: 2013-12-02 12:00:40 作者: rapoo

一个用带参宏定义字符串的语法
我有一个系列的字符串,大概是 little_pig_location_1,little_pig_location_2 这样一个系列

之前用了一堆土办法的宏定义了5个location,现在要加到50个,就不能再每个都挨个定义了。

找了一些办法,但是没有通过编译,求解

#define HEADER "little_pig_location_"
#define GetVersion(x) HEADER##x
printf("%s\n", GetVersion("version1"));


[解决办法]
用ssprintf函数,或者是直接用字符串数组,例如:
char str[32];
ssprintf(str, "little_pig_location_%d", version);

引用:
我有一个系列的字符串,大概是 little_pig_location_1,little_pig_location_2 这样一个系列

之前用了一堆土办法的宏定义了5个location,现在要加到50个,就不能再每个都挨个定义了。

找了一些办法,但是没有通过编译,求解

#define HEADER "little_pig_location_"
#define GetVersion(x) HEADER##x
printf("%s\n", GetVersion("version1"));

[解决办法]
[ codes]$ ./main 
loc1=little_pig_location_0 loc2=little_pig_location_1
[ codes]$ cat main.cc
#include <stdio.h>

#define make_str(token) #token
#define make_word(index) make_str(little_pig_location_##index)

int main(int argc, char *argv[])
{
const char *loc1 = make_word(0);
const char *loc2 = make_word(1);
printf("loc1=%s loc2=%s\n", loc1, loc2);
return 0;
}

读书人网 >C语言

热点推荐