如何获得printf样式的编译时警告或错误

Hip*_*der 12 c++ compiler-construction printf typechecking

我想写一个像printf这样的例程,而不是功能上的,但是我希望例程能够像printf一样编译检查特性.

例如,如果我有:

{
   int i;
   std::string s;
   printf("%d %d",i);
   printf("%d",s.c_str());
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨如下:

1 cc1plus: warnings being treated as errors
2 In function 'int main()':
3 Line 8: warning: too few arguments for format
4 Line 9: warning: format '%d' expects type 'int', but argument 2 has type 'const char*'
Run Code Online (Sandbox Code Playgroud)

代码示例

printf和co是编译器对待的特殊函数,还是有一些技巧可以让它在任何用户定义的函数上工作?我感兴趣的具体编译器是gcc和msvc

AnT*_*AnT 19

不同的编译器可能以不同方式实现此功能 在GCC中,它通过__attribute__format属性的说明符实现(在此处阅读).编译器执行检查的原因只是在GCC提供的标准头文件printf中声明了函数__attribute__((format(printf, 1, 2)))

以完全相同的方式,您可以使用formatattribute将相同的格式检查功能扩展到您自己的使用相同格式说明符的可变参数函数printf.

只有在您使用的参数传递约定和格式说明符与标准printfscanf函数使用的参数相同时,这一切才有效.检查被硬编码到编译器中.如果您使用不同的变量参数传递约定,编译器将无法帮助您检查它.

  • 它可以比printf和scanf做更多一点; 当前文档中的列表是"printf,scanf,strftime,gnu_printf,gnu_scanf,gnu_strftime或strfmon" (4认同)
  • 这很酷.我希望CodeGear/Embarcadero将来可以将这个功能放到他们的编译器中. (2认同)

dmc*_*kee 5

此行为高度依赖于编译器.我相信gcc为类型检查可变参数函数提供了一个接口.