Linking extern variables in C

José M. Gilgado picture José M. Gilgado · May 18, 2009 · Viewed 12.2k times · Source

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?

Answer

Chris Lutz picture Chris Lutz · May 18, 2009

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;
}