tags:

views:

1852

answers:

1

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

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

In MyLic.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

Thanks in advance.

+16  A: 

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
Thank you, I've just understood.
Polar Geek
No problem. The numerous stages of compilation can be pretty confusing at first.
Chris Lutz
@Chris Lutz good explanation. 1+ for you :)
mahesh