我希望看到我的代码 (C++) 中所有忽略函数返回值的地方。我该怎么做 - 使用 gcc 或静态代码分析工具?
错误的代码示例:
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;
}
请注意:
- 即使函数及其使用在不同的文件中,它也应该可以工作
- 免费静态检查工具
最佳答案
你想要 GCC 的 warn_unused_result
属性:
#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;
}
尝试编译这段代码会产生:
$ gcc test.c
test.c: In function `main':
test.c:16: warning: ignoring return value of `f', declared with
attribute warn_unused_result
您可以在 Linux kernel 中看到它的使用;他们有一个 __must_check
宏来做同样的事情;看起来你需要 GCC 3.4 或更高版本才能工作。然后你会发现内核头文件中使用了那个宏:
unsigned long __must_check copy_to_user(void __user *to,
const void *from, unsigned long n);
关于c++ - 如果忽略返回值,如何发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216757/