Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking extern variables in C

Tags:

c

extern

In Unix, I have got three main files. One of them is a library and the other one is a program.

  • MyLib.c and MyLib.h are the library.
  • main.c is the program.

In MyLib.h I have a declaration (extern int Variable;). When I try to use Variable in main.c I cannot. Of course I have included MyLib.h in MyLib.c and in main.c, and I link them too. Anyway the variable is not recognized in main.c.

How do I get the variable available when I link the program?

like image 572
José M. Gilgado Avatar asked May 17 '09 22:05

José M. Gilgado


1 Answers

Variable must be defined somewhere. I would declare it as a global variable in MyLib.c, and then only declare it as extern in main.c.

What is happening is that, for both MyLib.c and main.c, the compiler is being told that Variable exists and is an int, but that it's somewhere else (extern). Which is fine, but then it has to actually be somewhere else, and when your linker tries to link all the files together, it can't find Variable actually being anywhere, so it tells you that it doesn't exist.

Try this:

MyLib.c:

int Variable;

MyLib.h:

extern int Variable;

main.c:

#include "MyLib.h"

int main(void)
{
    Variable = 10;
    printf("%d\n", Variable);
    return 0;
}
like image 109
Chris Lutz Avatar answered Oct 05 '22 02:10

Chris Lutz