严格意义上的声明和定义并不相同!
下面看一个例子:
test.c:
#include <stdio.h> #include <malloc.h> extern int g_var; //声明 extern struct Test; //声明 int main() { extern void f(int i, int j); //声明 extern int g(int x); //声明 struct Test* p = NULL; // (struct Test*)malloc(sizeof(struct Test)); printf("p = %p\n", p); //g_var = 10; printf("g_var = %d\n", g_var); f(1, 2); printf("g(3) = %d\n", g(3)); free(p); return 0; }
global.c:
#include <stdio.h> /*下面都是定义*/ int g_var = 10; struct Test { int x; int y; }; void f(int i, int j) { printf("i + j = %d\n", i + j); } int g(int x) { return (int)(2 * x + g_var); }
输出结果如下:
怎么证明声明和定义不同呢?我们对 test.c 修改成这样,将 struct Test* p = NULL; 改成 struct Test* p = (struct Test*)malloc(sizeof(struct Test));
#include <stdio.h> #include <malloc.h> extern int g_var; extern struct Test; int main() { extern void f(int i, int j); extern int g(int x); struct Test* p = (struct Test*)malloc(sizeof(struct Test)); printf("p = %p\n", p); //g_var = 10; printf("g_var = %d\n", g_var); f(1, 2); printf("g(3) = %d\n", g(3)); free(p); return 0; }
可以看到,直接报错:
delphi@delphi-vm:~$ gcc test.c global.c
test.c:6: warning: useless storage class specifier in empty declaration
test.c: In function ‘main’:
test.c:13: error: invalid application of ‘sizeof’ to incomplete type ‘struct Test’
这是因为编译器在 test.c 是找不到 struct Test 的定义的,只有 struct Test 的声明,因此无法知道 struct Test 结构体的信息。(C 语言编译器编译 C 文件的时候不会依赖于文件之间的编译顺序)。