Search code examples
cexternos161

How to share one variable between 2 .c files?


Consider a variable abulo. I am trying to share abulo between 2 .c files. Here is what I did --

  1. Created a.h . This file contains the line, extern int abulo;
  2. a.c contains a statement like this, int abulo = 0;
  3. in b.c, a.h has been included. Then there is just a kprintf function printing the value of yours.

But when I try to run the code it shows me an output like this --

undefined reference to `abulo'

Tried to use the idea of the accpeted answer given here - How do I share variables between different .c files?

what am I doing wrong here ? How to get rid of this error ?


Solution

  • You should link a.o when building the executable. Example:

    cc -c a.c
    cc -c b.c
    cc a.o b.o -o executable
    #  ^^^ this is important