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

如何强制GCC对非字面量格式字符串执行printf参数检查?

GCC对const常量格式字符串的参数类型检查问题

以下是一段C语言代码:

const char* const non_literal_string = "Hello %d";

void my_print()
{
    /* 
     * 我希望GCC编译此行时抛出警告,因为传入的参数不是int类型。
     */
    printf(non_literal_string, "World!");
    
    // 就像它对此行做的检查一样
    printf("Hello %d", "World!");
}

我已将non_literal_string声明为const char* const,意味着指针和指向的字符串均不可修改,因此GCC具备检查传入参数是否匹配格式字符串类型的条件。

使用Clang编译器时,即使是非字面量格式字符串也会执行此类检查,以下是Clang编译该代码的中文输出:

<source>:11:32: 警告:格式字符串要求类型为'int',但参数类型为'char *' [-Wformat]
   11 |     printf(non_literal_string, "World!");
      |            ~~~~~~~~~~~~~~~~~~  ^~~~~~~~
<source>:3:47: 备注:格式字符串定义于此
    3 | const char* const non_literal_string = "Hello %d";
      |                                               ^~
      |                                               %s
<source>:14:24: 警告:格式字符串要求类型为'int',但参数类型为'char *' [-Wformat]
   14 |     printf("Hello %d", "World!");
      |                   ~~   ^~~~~~~~
      |                   %s

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 00:28:10