Art*_*sky 5 c declaration function implicit function-prototypes
当我的程序包含两个文件时:
main.c中
#include <stdio.h>
int main(void) {
printf("%lf\n",f());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
func.c
double f(int a) {
return 1;
}
Run Code Online (Sandbox Code Playgroud)
编译器不显示任何错误.
当我的程序只包含一个文件时:
main.c中
#include <stdio.h>
int main(void) {
printf("%lf\n",f());
return 0;
}
double f(int a) {
return 1;
}
Run Code Online (Sandbox Code Playgroud)
Visual C++ 2008编译器显示以下错误:
Error 2 error C2371: 'f' : redefinition; different basic types d:\temp\projects\function1\function1\1.c 8 function1
Run Code Online (Sandbox Code Playgroud)
任何人都能解释这种奇怪的行为吗?
C将假设一个函数具有原型int func(); 除非你另有说明.(注意在C int func();和int func(void);是不同的东西)
在第二种情况下,您调用f()编译器没有看到任何原型,因此它假定它是int f();.稍后它会看到您的定义f()具有不同的原型 - 并发出错误.
这种情况不会发生在1.情况下,因为它们位于不同的编译单元中.
这两个程序都错了.
如果没有范围内的原型,编译器会假定函数返回int并采用未指定数量的参数.
让我们稍微改变你的文件:
$ cat func.c
double f(int a) {
return 1.0;
}
$ cat main.c
#include <stdio.h>
int main(void) {
double d = f();
printf("%lf\n", d);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,gcc警告我(Visual C++也应该在符合模式下).但是让我们忽略这个警告.
$ gcc -std=c99 -pedantic -W -Wall func.c main.c -o test
func.c:1: warning: unused parameter 'a'
main.c: In function 'main':
main.c:4: warning: implicit declaration of function 'f'
$ ./test
0.000000
Run Code Online (Sandbox Code Playgroud)
它没有打印1,而是打印0.这是因为编译器假定f()返回了一个int,并且赋值d = f();将" int" 转换为a double.编译器仍然编译代码,因为它无法判断f()它是否以(隐式)声明的方式定义.但是标准不要求编译上面的程序,所以编译器可能会拒绝它(gcc -Werror例如尝试!)
如果我们在一个文件中包含所有内容
$ cat func.c >>main.c
$ gcc -std=c99 -pedantic -W -Wall func.c main.c -o test
main.c:4: warning: implicit declaration of function 'f'
main.c: At top level:
main.c:9: error: conflicting types for 'f'
main.c:4: error: previous implicit declaration of 'f' was here
main.c:9: warning: unused parameter 'a'
Run Code Online (Sandbox Code Playgroud)
现在编译器会看到冲突,并给出错误消息.但是,编译器不需要拒绝上述程序,它可能会也可能不会.
大多数编译器不拒绝第一个程序,因为他们不知道您是否f()在另一个翻译单元中有正确的功能定义.他们拒绝第二个程序,因为他们知道你没有.