Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "extern struct" to share variables in c programming and compile with gcc?

Tags:

c

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?

like image 225
LambdaG Avatar asked Jan 16 '23 01:01

LambdaG


1 Answers

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.

like image 143
Jay Avatar answered Feb 16 '23 03:02

Jay