2013-03-05 48 views
5

我们有了一个方法可以做到这一点...我可以使用C-preprocssor将整数转换为字符串吗?

我有一个头文件,version.h中有一条线......

#define VERSION 9 

和一些文件使用定义的版本价值作为整数。 这很好。

不改变版本的方式定义,我需要建立一个 初始化“是什么”,其中包含价值, 所以我需要这样的字符串...

char *whatversion = "@(#)VERSION: " VERSION; 

显然,这并不编译,所以不知何故,我需要得到一个 字符串版本根本上给这个预处理值的...

char *whatversion = "@(#)VERSION: " "9"; 

任何想法? 这可能吗?

回答

0

里面一个宏之前,您可以使用“字符串”运算符(#),这将不正是你想要什么:

#define STR2(x) #x 
#define STR(x) STR2(x) 
#define STRING_VERSION STR(VERSION) 

#define VERSION 9 

#include <stdio> 
int main() { 
    printf("VERSION = %02d\n", VERSION); 
    printf("%s", "@(#)VERSION: " STRING_VERSION "\n"); 
    return 0; 
} 

是的,你确实需要双宏调用中的间接寻址。没有它,你会得到"VERSION"而不是"9"

您可以在gcc manual(尽管它是完全标准的C/C++)中阅读更多关于此的内容。

+0

完美!非常感谢! – 2013-03-06 12:59:57

5

它不是数据类型,它是一个标记。一团文字。

K & R说说串联值:

The preprocessor operator ## provides a way to concatenate actual arguments 
during macro expansion. If a parameter in the replacement text is adjacent 
to a ##, the parameter is replaced by the actual argument, the ## and 
surrounding white space are removed, and the result is re-scanned. For example, 
the macro paste concatenates its two arguments: 

    #define paste(front, back) front ## back 

    so paste(name, 1) creates the token name1. 

- 尝试。 #定义字符串你到char *version=

+0

您只能将令牌粘贴在一起,这非常有限。例如,你不能轻易生成一个字符串,'#(@)VERSION'不是一个标记,所以它不能和任何东西串联。 (''#(@)VERSION“'是一个标记,但是不能将字符串标记连接到另一个标记,除非该标记是长度标记。幸运的是,您不需要连接字符串标记。) – rici 2013-03-06 00:14:46