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.
只有在您使用的参数传递约定和格式说明符与标准printf和scanf函数使用的参数相同时,这一切才有效.检查被硬编码到编译器中.如果您使用不同的变量参数传递约定,编译器将无法帮助您检查它.
| 归档时间: |
|
| 查看次数: |
5678 次 |
| 最近记录: |