我希望在源文件main.c和second.c之间访问一些共享变量,我的头文件是all.h定义了共享数据类型,
#ifndef ALL_H
#define ALL_H
struct foo {
double v;
int i;
};
struct bar {
double x;
double y;
};
#endif
main.c在下面给出
/* TEST*/
#include "all.h"
#include "second.h"
int main(int argc, char* argv[])
{
struct foo fo; // should be accessed in second.c
fo.v= 1.1;
fo.i = 12;
struct bar ba; // should be accessed in second.c
ba.x= 2.1;
ba.y= 2.2;
sec(); // function defined in second.c
return 0;
}
second.h在下面给出
#include <stdio.h>
#include "all.h"
int sec();
second.c在下面给出
#include "second.h"
extern struct foo fo;
extern struct bar ba;
int sec()
{
printf("OK is %f\n", fo.v+ba.x);
return 0;
}
我以为我拥有所有声明并包含标题。但是当我编译
gcc -o main main.c second.c
or
gcc -c second.c
gcc -c main.c
gcc -o main main.o second.o
它会给出一些错误,例如
second.o: In function `sec':
second.c:(.text+0x8): undefined reference to `fo'
second.c:(.text+0xe): undefined reference to `ba'
collect2: ld returned 1 exit status
我认为某处的使用extern
是错误的还是我使用gcc
不正确?