c - 使用标记为 __unused 的参数时发出警告

标签 c clang

使用 -Wunused-parameter 标志,您可以对未使用的参数强制执行 __unused,作为编译器优化。以下代码会导致两个警告:

#include <stdio.h>
int main(int argc, char **argv) {
  printf("hello world\n");
  return 0;
}

通过添加 __unused 未使用的参数来修复这些警告。

#include <stdio.h>
int main(int __unused argc, char __unused **argv) {
  printf("hello world\n");
  return 0;
}

当您使用标记为 __unused 的参数时,clang 4.1 不会发出警告或错误。

#include <stdio.h>
int main(int __unused argc, char __unused **argv) {
  printf("hello world. there are %d args\n", argc);
  return 0;
}

使用 __attribute__((unused)) 表现出相同的行为。

int main(int __attribute__((unused)) argc, char __attribute__((unused)) **argv) {

有没有办法在 __unused 上发出警告或错误?如果您不小心将 __unused 留在已使用的参数上,会发生什么?在上面的示例中,argc 似乎具有正确的值,尽管它可能是编译器没有利用该提示,如果没有更多的了解,我不会依赖这种行为。

最佳答案

__unused 属性旨在防止在函数/方法或函数/方法的参数未使用时出现投诉,而不是强制它们不被使用。

GCC manual 中使用的术语是:

This attribute, attached to a function, means that the function is meant to be possibly unused

for variables :

This attribute, attached to a variable, means that the variable is meant to be possibly unused.

最常见的用途是针对接口(interface)进行开发 - 例如回调,您可能被迫接受多个参数,但不要使用所有参数。

我在进行测试驱动开发时会稍微使用它 - 我的初始例程采用一些参数但什么都不做,因此所有参数都采用 __attribute__((unused))。在我开发它时,我使用了参数。在开发结束时,我将它们从方法中移除,然后看看会产生什么。

关于c - 使用标记为 __unused 的参数时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492637/

相关文章:

c++ - 编译时抽象类处理中的 clang vs gcc

c++ - Clang 看不到 strdup 和其他一些函数

c - 为什么 -fno-stack-protector 会颠倒这些字符串的存储顺序?

c - KdTree C 实现导致核心转储

c - O(1) 代码来计算一个范围内数字的倍数?

C:插入排序逻辑无法使用指针和结构来工作

java - 快速准确的稀疏 svd 库?

objective-c - Objective-C 中是否有一些文字字典或数组语法?

c++ - 由于在 Bjarne Stroustrup "Programming and Practices using c++"中找不到符号导致的链接错误

c++ - libstdc++ 不识别标准库文字