整个源文件中的头文件是否重复?

Nig*_*ley 2 c gcc c99

// File foo1.c :
#include <stdio.h> // once
void foo1(void);
void foo1(void){
    puts("foo1");
}

// File foo2.c :
#include <stdio.h> // again
void foo2(void);
void foo2(void){
    puts("foo2");
}

// File foomain.c :
#include <stdio.h> // yet again
void foo1(void); // again
void foo2(void); // again
int main(void){
    foo1();
    foo2();
    puts("foomain");
    return 0;
}

// create object files
gcc -fPIC foo1.c -o foo1.o // 1 stdio.h
gcc -fPIC foo2.c -o foo2.o // 1 stdio.h

// create shared library
gcc -fPIC -shared foo1.o foo2.o -o foo.so // foo.so contains stdio.h 2 times ?

// build entire program
gcc foo.so foomain.c -o foomain // foomain contains 1 stdio.h plus the 2 from foo.so ?
Run Code Online (Sandbox Code Playgroud)
  1. 为什么整个程序包含3个stdio.h?似乎多余,为什么不只是1?编译器不应该只需要1吗?

  2. 对象文件包含原型是有意义的,但为什么必须在foomain.c中再次指定它们?编译器不应该知道它们已经在foo.so中指定了吗?

par*_*eek 6

那是因为每个文件都是单独编译的,所以每次编译器都应该知道用于执行编译时检查的所有函数的签名.因此,每个文件都必须包含所有使用的声明,这些声明在编译文件之前由预处理器包含.