最近了解到有parameter-type-lists在 C 中可以为空:
int print();
int main() {
print("hallo"); // << valid but highly unintuitive
}
int print() {
}
在这段代码中,有人可能只是忘记了编写 print(void)
(可能是 C++ 开发人员),但其他人提供了一个参数。编译不显示任何警告或错误:
$ make test -Wstrict-prototypes -Wimplicit -Wimplicit-function-declaration -Wall
cc test.c -o test
我没有找到警告空参数类型列表的编译器标志,仅针对隐式函数声明。
我能做些什么来帮助我找到给定代码库中参数类型列表的所有用途吗?
例如
- letting a C++ compiler compile the C code as C++并解决类型问题(如果声明未列出参数,C++ 不允许参数)
- 让编译器列出所有函数声明(不知道是否可能)并手动搜索空括号
grep
参数类型列表(对我来说太复杂了:))- 通过编译器开关禁用参数类型列表(未找到)
最佳答案
对于 gcc,使用 -Wstrict-prototypes 将实现您的预期:
-Wstrict-prototypes (C and Objective-C only) Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration that specifies the argument types.)
以你的例子,它给出:
hallo.c:1:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
int print() {
^
但是,您必须确保现有代码中的所有非严格函数声明都得到正确定义;特别是,没有参数的函数应该用 (void) 声明,如下所示:
int print(void);
关于c - 如何在 C 代码库中找到参数类型列表的使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911835/