这个问题源于试图理解“C 哲学”,而不是源于任何“真正的问题”。
假设在 C 程序中我使用 sin(x):
#include <stdio.h>
int main() {
char s[20] = "aha";
printf("%f", sin(s));
return 0;
}
我故意犯了两个错误:
- 我没有
#include
ed math.h(或者提供任何关于 sin 的声明)。 - 我将其制成了
s
类型char *
(只是一些无法有意义地转换为的东西double
)。
我使用带有-lm
标志的 GCC 进行编译。
正如预期的那样,我收到一个警告和一个错误。
当然,还有函数隐式声明的警告等等:
bad.c: In function ‘main’:
bad.c:5:15: warning: implicit declaration of function ‘sin’ [-Wimplicit-function-declaration]
5 | printf("%f", sin(s));
| ^~~
bad.c:5:16: warning: incompatible implicit declaration of built-in function ‘sin’
bad.c:2:1: note: include ‘<math.h>’ or provide a declaration of ‘sin’
1 | #include <stdio.h>
+++ |+#include <math.h>
一些研究似乎表明,如果一个函数事先没有声明,那么 C 会假定一个“默认声明”(所谓的“隐式声明”),就像int undeclaredfunction(void)
。
但我也收到以下错误:
2 |
bad.c:5:19: error: incompatible type for argument 1 of ‘sin’
5 | printf("%f", sin(s));
| ^
| |
| char *
bad.c:5:20: note: expected ‘double’ but argument is of type ‘char *’
这表明“隐式声明”需要一个类型的参数double
。
- 似乎 C 维护着“标准函数”的正确“隐式声明”列表。在哪里可以找到给定编译器(例如
gcc
或clang
)的正确隐式声明的完整列表? - 如果 C 已经内置了标准数学函数的正确声明,那么为什么它还要求程序员这样做呢
#include<math.h>
? 只是因为传统? 还是为了简洁?
我寻找的答案是关于编译器使用的确切规则,而不是关于“良好编程实践”的主观评论。