有三个文件ex1.c ex1.h main.c想来测试一下多文件共同编译时,他们的"共同变量"究竟是有着怎样的关系
ex1.c:
#include "ex1.h"
int a=0;
void numadd()
{
a++;
b++;
}
ex1.h
#ifndef EX1_HH
#define EX1_HH
#include <stdio.h>
void numadd();
#endif
main.c
#include "ex1.h"
int b=0;
void main()
{
numadd();
printf("a=%d\nb=%d\n",a,b);
}
Makefile
$(Target)=result.out
$(Object)=ex1.o main.o
$(Target):$(Object)
gcc $(Object) -o $(Target)
这里用makefile纯属练手,实则没必要
思路是在ex1.c的函数外定义一个全局变量a,在main.c的函数外定义一个全局变量b
在ex1.c中写一个让a,b自加的函数,如果照着上面的函数运行的话就会出错,原因是没有在main.c中检测到a,同时在ex1.c中也没有检测到b,如果在ex1.h中定义一个extern int a;可以解决a的问题,同样在ex1.c中extern int b可以解决这个问题。
如果将a,b定义在函数里面,那么即便再使用extern,仍然无济于事。