我可以使用C-preprocssor将整数转换为字符串吗?

Ed.*_*Ed. 5 c

必须有办法做到这一点......

我有一个头文件,version.h有一行...

#define VERSION 9
Run Code Online (Sandbox Code Playgroud)

一些文件使用VERSION的定义值作为整数.没关系.

在不改变定义VERSION的方式的情况下,我需要构建一个包含该值的初始化"what"字符串,所以我需要这样的东西......

char *whatversion = "@(#)VERSION: " VERSION;
Run Code Online (Sandbox Code Playgroud)

显然这不会编译,所以不知怎的,我需要得到一个VERSION的预处理值的字符串,基本上给这个...

char *whatversion = "@(#)VERSION: " "9";
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?这可能吗?

jim*_*ara 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.
Run Code Online (Sandbox Code Playgroud)

- 试试看.在你到达之前#define字符串char *version=


ric*_*ici 0

在宏内部,您可以使用“stringify”运算符(#),它将完全按照您的要求进行操作:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

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