1.test.h
#ifndef TEST_H
#define TEST_H
/*
这里只是说明,在头文件中定义变量是不被推荐的。
*/
int a = 0;
int b = 0;
int c = 0;
int test();
#endif
注意:#ifndef只能防止.h文件被同一个C文件重复包含;不能保证两个C文件对其两次包含,所以如果被一个模块(编译成一个so或bin)中两个c同时包含、并且h文件中有上述定义(非声明)。编译系统就会在链接阶段出错。换句话说:#ifndef是在编译阶段起作用。
这告诉我们:永远不要在.h文件中定义变量!定义变量和声明变量的区别在于定义会产生内存分频操作,是汇编阶段的概念;而声明则只是告诉包含该声明的模块在连接阶段从其他模块寻找外部函数和变量。
但仍然需要注意:声明不一定不是定义,但定义一定是定义!因为有的编译器在int a时已经分配内存,并给予一个零值;但extern一定只是声明。
2.test.c
#include <stdio.h>
/*
如下头文件包含后报错
cc -c main.c test.h
cc -c test.c test.h
cc -o main main.o test.o
test.o:(.bss+0x0): multiple definition of `a'
main.o:(.bss+0x0): first defined here
test.o:(.bss+0x4): multiple definition of `b'
main.o:(.bss+0x4): first defined here
test.o:(.bss+0x8): multiple definition of `c'
main.o:(.bss+0x8): first defined here
*/
//#include "test.h"
extern int a;
extern int b;
extern int c;
int test(){
a = 5; b = 3; c = 100;
printf("aadda\n");
return 0;
}
extern关键字是在模块间链接阶段起作用。
3.main.c
#include "test.h"
#include <stdio.h>
int main(){
a = 5; b = 3; c = 10;
printf("aadda\n");
test();
return 0;
}
4.Makefile
objects = main.o test.o
default:
cc -c main.c
cc -c test.c
cc -o main $(objects)
clean:
rm *.o main