You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C宏字符串化正确处理含单引号的内容?

解决C宏字符串化中的单引号问题

问题分析

你当前的宏myprint使用#s进行字符串化时,遇到两个核心问题:

  • 直接传递带单引号的无引号文本(如I'm happy)会触发语法错误,因为预处理器会将单引号视为字符常量的起始标记,导致参数解析失败。
  • 传递带双引号的文本(如"I'm happy")虽然能运行,但输出会包含多余的双引号,不符合预期。

解决方案

通过字符串化后自动剥离首尾双引号的逻辑,可同时兼容两种调用方式并得到正确输出。以下是修改后的代码:

#include <stdio.h>
#include <string.h>

#define STRIP_QUOTED_STRING(s) \
    do { \
        const char* str = (#s); \
        size_t len = strlen(str); \
        if (len >= 2 && str[0] == '"' && str[len-1] == '"') { \
            printf("passed string: %.*s\n", (int)(len-2), str+1); \
        } else { \
            printf("passed string: %s\n", str); \
        } \
    } while(0)

// 简化调用的宏
#define myprint(s) STRIP_QUOTED_STRING(s)

int main ()
{
    myprint(print this);          // 输出: passed string: print this
    myprint("I'm happy");         // 输出: passed string: I'm happy
    myprint(I\'m happy);          // 转义单引号后直接传参,输出: passed string: I'm happy
    return 0;
}

针对Apache Traffic Server的适配

你需要为Apache Traffic Server添加418 I'm a teapot的支持,相关代码位于Apache Traffic Server源码的src/proxy/hdrs/HTTP.cc文件第832至833行。可套用上述逻辑:将带单引号的字符串用双引号包裹后传入宏,通过引号剥离逻辑得到不含多余双引号的目标文本。

内容的提问来源于stack exchange,提问作者firebush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 08:35:31