15

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
José M. Gilgado
  • 1,314
  • 3
  • 14
  • 21
  • Please post the source and the error. In particular, how have you managed to link when you cannot even build main.c ? – Macker May 17 '09 at 22:35
  • I had a main.c overthere, and I was just triying to understand how the compiler and linker work. But Chris Lutz's answer worked. Thanks. – José M. Gilgado May 17 '09 at 22:40

1 Answers1

31

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;
}
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183