c++ - 如果忽略返回值,如何发出警告?

标签 c++ c gcc static-analysis

我希望看到我的代码 (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/

相关文章:

c - C 中的三元组求和

C++98 花括号 const 标量初始化

c - gcc -O3 选项如何使运行速度如此之快?

c++ - 使用堆栈获取 BST 的高度

c++ - 找到气体容器的最小必要体积

c++ - 不可预测的伪RNG

c++ - 编译器是否允许进行这样的优化?

c - 接收字符串时出现截断错误

c - 如何在不加载图像的情况下在opencv上绘制矩形/圆形

c++ - MSVC 和 GCC 之间的 vector 行为不同