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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With