gcc myvar undeclared & undefined references to myvar /// usage of extern vatiables

3 posts / 0 new
Last post
JosDuchIt
JosDuchIt's picture
Offline
Last seen: 8 years 3 days ago
Joined: 2012-01-08 20:57
gcc myvar undeclared & undefined references to myvar /// usage of extern vatiables

I have a real strange & frustrating experience here:
While trying to iron out another problem, i suddenly got a lot of undefined references to a number of variables and structures i had declared (say myvar is one of them) as extern in my gui-protos.h file.
I deleted them there and added them to gui.c where i have my main() function.
The problem did not disappear. I tried at different places with regard to my includes to no avail. I then just put the declaration as well in gui-protos.h
and gui.c and now got understandable errors pointing me to the last redefined variable.
I also had an error of 'myvar undeclared' in main where myvar was the first one used in main (myvar = 0; )
Stripping them from gui.c brings me back to the previous situation: lots of undefined references.

What can i have done to get into this situation ? How can i detect it??

billyfish
billyfish's picture
Offline
Last seen: 3 years 10 months ago
Joined: 2012-01-23 20:45
I'm not sure if it's the

I'm not sure if it's the situation you've got but variables can be declared as extern any amount of times but have to be non-extern once. I use a trick that I got from a Paul Overaa book years ago and have something like this in a header file, globals.h, say.

  1. #ifdef ALLOCATE_GLOBALS
  2. #define PREFIX
  3. #else
  4. #define PREFIX extern
  5. #endif
  6.  
  7. /* The variables */
  8. PREFIX struct Foo bar;
  9. ....

Then any file can include this header to get the variables as extern references and in just one file have ALLOCATE_GLOBALS prior to including "globals.h" e.g.

  1. /* allocate our global variables. */
  2. #define ALLOCATE_GLOBALS
  3. #include "globals.h"

All the other modules can simply just include globals.h to get their extern references.

Hope this helps

billy

JosDuchIt
JosDuchIt's picture
Offline
Last seen: 8 years 3 days ago
Joined: 2012-01-08 20:57
@billyfish. Thanks. You

@billyfish.
Thanks. You pointed me in the right direction and made me look more closely to the use of extern variables.
The author of the source i am working on seems to have followed the guidelines described here
http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c
so i'll continue using these.

Log in or register to post comments