这是使用fork()来展示它是如何工作的代码(fork.c)。
gcc --version
显示gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
#include <stdio.h>
int num = 0;
int main(int argc, char*argv[]){
int pid;
pid = fork();
if(pid == 0){ /*child*/
num = 1;
}else if(pid > 0){ /*parent*/
num = 2;
}
printf("%d", num);
}
然后gcc fork.c -o fork
进行编译。它编译时没有任何错误,可执行文件正确运行。但我没有明确包含头文件unistd.h
,我还检查了所有递归包含的头文件(gcc -H
)
. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h
然后我在所有文件中都grep
但我没有找到任何fork()声明。
如果从未在任何头文件中声明fork(),它怎么能编译而没有任何错误?或者我错过了什么?
答案 0 :(得分:6)
在旧版本的C(C99之前:C89或K&amp; R C)中,您不需要声明来调用函数。然后,您有责任提供正确的参数数量和类型,并且假定返回值为int
类型。编译器不为此案例提供任何正确性检查。
main.cpp: In function 'main':
main.cpp:5:11: warning: implicit declaration of function 'fork' [-Wimplicit-function-declaration]
pid = fork();
^~~~
答案 1 :(得分:2)
In addition to what Ilya Popov said about declarations, function fork()
is included in the standard C library, libc
, which is implicitly linked with the object files when you build your project. This inclusion does not guarantee that the function is called correctly, but it guarantees its presence.