使用 -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
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/