Reputation: 148
I want some shared variables should be accessed among source files, main.c and second.c and my header file is all.h defined the shared data type,
#ifndef ALL_H
#define ALL_H
struct foo {
double v;
int i;
};
struct bar {
double x;
double y;
};
#endif
main.c is given below
/* 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 is given below
#include <stdio.h>
#include "all.h"
int sec();
second.c is given below
#include "second.h"
extern struct foo fo;
extern struct bar ba;
int sec()
{
printf("OK is %f\n", fo.v+ba.x);
return 0;
}
I thought i have all the declaration and include the headers. But when i compile
gcc -o main main.c second.c
or
gcc -c second.c
gcc -c main.c
gcc -o main main.o second.o
It will give some error like
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
I think somewhere of the use of extern
was wrong or i use the gcc
incorrectly?
Upvotes: 5
Views: 68415
Reputation: 1020
main.h:
typedef struct
{
double v;
int i;
} Foo;
extern.h:
extern Foo fo; // "fo is a global variable stored somewhere else"
main.c:
#include "main.h"
#include "extern.h"
//use fo.v here
second.c:
#include "second.h"
#include "main.h"
#include "extern.h"
Foo fo; // "store the data of fo here"
//use fo.v here
Just include #include "main.h"
and #include "extern.h"
in all .c files you want to use fo
.
Notice that Foo fo
is only in second.c, nowhere else.
Upvotes: 3
Reputation: 169191
The error message indicates that the linker is unable to find fo
and ba
. With the extern
declaration you have told the compiler that the variables will exist in some other translation unit, but they don't.
You need to move the struct foo fo;
and struct bar ba;
outside of the main()
function. Right now, they are function local variables. They need to be global variables for this to work.
Upvotes: 3
Reputation: 24905
The problem is with the scope. Your variables (fo
& ba
) have local scope as they are declared within main
.So, their visibility is restricted to within main
function. Please make them global variables and it should work.
Upvotes: 7