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

wjl*_*wjl 8 c clang

使用-Wunused参数标志,可以将__unused强制用于未使用的参数,作为编译器优化.以下代码会导致两个警告:

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

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

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

当您使用标记为__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;
}
Run Code Online (Sandbox Code Playgroud)

使用相同的行为__attribute__((unused)).

int main(int __attribute__((unused)) argc, char __attribute__((unused)) **argv) {
Run Code Online (Sandbox Code Playgroud)

是否有办法在__unused上发出警告或错误?如果您不小心在已使用的参数上留下__unused,会发生什么?在上面的例子中argc似乎有正确的值,虽然它可能是编译器没有利用提示,并且我不会在没有更多理解的情况下依赖这种行为.

Pet*_*esh 12

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

GCC手册中使用的术语是:

附加到函数的此属性意味着该函数可能未使用

变量:

附加到变量的此属性表示该变量可能未使用.

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

当我进行测试驱动开发时,我会使用它 - 我的初始例程需要一些参数并且什么也不做,所以所有参数都需要__attribute__((unused)).在我开发它时,我使用了参数.在开发结束时,我从方法中删除它们,看看是什么震动了.

  • 这不是优化提示 - 调用约定会要求参数存在.与声明`register`变量的方式相同,如果没有任何寄存器可以使用,则不应该导致错误. (2认同)