如果返回值被忽略,如何提示警告? [英] How to raise warning if return value is disregarded?
问题描述
我想看看我的代码中的所有地方(C ++),它忽略了函数的返回值。如何使用gcc或静态代码分析工具?
不良代码示例:
int f(int z){
return z +(z * 2)+ z / 3 + z * z + 23;
}
int main()
{
int i = 7;
f(i); /////<< -----这里我忽略了返回值
return 1;
}
请注意:
- 即使该函数及其用途位于不同文件中,它也应该可以正常工作
- 免费静态检查工具
您希望GCC的 warn_unused_result
属性:
#define WARN_UNUSED __attribute __((warn_unused_result))
INT WARN_UNUSED f(int z){
返回z +(z * 2)+ z / 3 + z * z + 23;
}
int main()
{
int i = 7;
f(i); /////<< -----这里我忽略了返回值
return 1;
}
尝试编译此代码会产生:
$ gcc test.c
test.c:函数`main':
test.c:16:warning:忽略返回值`f',声明为
属性warn_unused_result
您可以在<一个href =http://lxr.linux.no/linux+v2.6.32/include/linux/compiler-gcc3.h#L16 =noreferrer> Linux内核;他们有一个 __ must_check
宏来做同样的事情;看起来你需要GCC 3.4或更高版本才能工作。然后你会发现这个宏在内核头文件中使用:
unsigned long __must_check copy_to_user(void __user * to,
const void * from,unsigned long n);
I'd like to see all the places in my code (C++) which disregard return value of a function. How can I do it - with gcc or static code analysis tool?
Bad code example:
int f(int z) {
return z + (z*2) + z/3 + z*z + 23;
}
int main()
{
int i = 7;
f(i); ///// <<----- here I disregard the return value
return 1;
}
Please note that:
- it should work even if the function and its use are in different files
- free static check tool
You want GCC's warn_unused_result
attribute:
#define WARN_UNUSED __attribute__((warn_unused_result))
int WARN_UNUSED f(int z) {
return z + (z*2) + z/3 + z*z + 23;
}
int main()
{
int i = 7;
f(i); ///// <<----- here i disregard the return value
return 1;
}
Trying to compile this code produces:
$ gcc test.c
test.c: In function `main':
test.c:16: warning: ignoring return value of `f', declared with
attribute warn_unused_result
You can see this in use in the Linux kernel; they have a __must_check
macro that does the same thing; looks like you need GCC 3.4 or greater for this to work. Then you will find that macro used in kernel header files:
unsigned long __must_check copy_to_user(void __user *to,
const void *from, unsigned long n);
这篇关于如果返回值被忽略,如何提示警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!