我有一个 C 函数,用于格式化具有以下签名的字符串:
int
string_format
( char* dst
, const char* fmt
, ...
);
我通常这样称呼它:
char buf[20];
const char* name = "Jeff";
string_format ( buf , "Hello %s!\n" , name );
我现在正在尝试使用 ANSI 颜色代码处理彩色文本。理想情况下,我想在我的字符串文字中使用它们,如下所示:
char buf[20];
const char* name = "Jeff";
string_format ( buf , COLOR_RED "Hello %s!\n" , name );
我写了一些宏来构建这些字符串文字,但我做错了一些事情。例如,我尝试过:
#define ANSI_CC(color) "\033["#color"m"
#define ANSI_CC_FG_RED "91"
#define COLOR_RED (ANSI_CC(ANSI_CC_FG_RED))
但是当我尝试调用
string_format (buf, COLOR_RED "Hello world.\n"")
时,我收到编译器错误:
error: expected ')' before string constant
| COLOR_RED "Hello world.\n"
^~~~~~~~~~~~~~~~
我的想法是预处理器会评估
COLOR_RED
如下:
COLOR_RED =>
(ANSI_CC(ANSI_CC_FG_RED)) =>
"\033["ANSI_CC_FG_RED"m" =>
"\033[""91""m"
但显然它正在做其他事情,我不明白;我怀疑我错误地使用了
#
字符串化运算符。有人可以解释一下预处理器对我编写的宏做了什么吗?另外,如果我想要实现的目标是可能的,我需要改变什么?
谢谢。
您的宏将扩展为:
string_format ( buf , ("\033[""ANSI_CC_FG_RED""m") "Hello %s!\n" , name );
您需要将宏更改为:
#define ANSI_CC(color) "\033[" color "m"
#define ANSI_CC_FG_RED "91"
#define COLOR_RED ANSI_CC(ANSI_CC_FG_RED)
它将扩展为:
string_format ( buf , "\033[" "91" "m" "Hello %s!\n" , name );