0

我正在尝试在另一个常量定义中使用常量定义,如下所示:

#define ADDRESS 5002
#define FIND "foundaddress ADDRESS"

但是当我希望找到常量 FIND 地址 5002 时,这包括 FIND 常量中的 ADDRESS。

有没有办法做到这一点?

4

4 回答 4

2

如果您不介意将 ADDRESS 更改为字符串,则可以使用预处理器连接

#define ADDRESS "5002" /* rather than 5002 without quotes */
#define FIND "foundaddress " ADDRESS

编译器会将第二行视为

#define FIND "foundaddress 5002"
于 2013-04-18T19:13:09.327 回答
2

您需要使用预处理器字符串化运算符将您的值转换为字符串,然后像其他人所说的那样将它们连接起来。

#define ADDRESS_TO_STRING(x) #x
#define ADDRESS 5002
#define FIND "foundaddress " ADDRESS_TO_STRING(ADDRESS)

如果这给了您“foundaddress ADDRESS”,则意味着您需要多一层:

#define ADDRESS_TO_STRING_(x) #x
#define ADDRESS_TO_STRING(x) ADDRESS_TO_STRING_(x)
#define ADDRESS 5002
#define FIND "foundaddress " ADDRESS_TO_STRING(ADDRESS)
于 2013-04-18T19:13:15.873 回答
1

是的。

#define ADDRESS "5002"
#define FIND "foundaddress " ADDRESS
于 2013-04-18T19:09:26.720 回答
0

C/C++ 宏字符串连接

/*
 * Turn A into a string literal without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define STRINGIZE_NX(A) #A

/*
 * Turn A into a string literal after macro-expanding it.
 */
#define STRINGIZE(A) STRINGIZE_NX(A)

然后

#define FIND ("foundaddress " STRINGIZE(ADDRESS))

产生 ("foundaddress " "5002") ,由于 C 的字符串文字连接,它应该可以在您需要字符串文字的任何地方使用。

于 2013-04-18T19:16:04.510 回答