Home Extern Variables seemingly not working
Reply: 1

Extern Variables seemingly not working

Matthew Kerian
1#
Matthew Kerian Published in 2017-12-04 18:52:10Z

I've been searching through Stackoverflow and the web for the answer and it seems like I'm doing this correctly, however I can't get it to work.

I made a test program for using extern, (it's on xCode using the projects feature if that makes a difference). I'm trying to declare a variable, that I can access anywhere in my program, whenever I change the value of that variable, I want to be able to access the changed value.

What I've done so far is I have a header file

 externFile.h

and a

externFile.c

and of course my main.c

In externFile.h I defined:

 extern int ply;

In main.c I have:

int main()
{
   int ply;
   ply = 5;
   printPly();
}

In externFile.c I have:

 void printPly(){
 printf("%d is ply.\n", ply);
 }

However I'm getting this error:

 _ply referenced from _printPly
 ld symbols not found for architecture x86_64

Does anyone have any sort of ideas about this?

EDIT: Thanks for the help Weathervane and Eugene!

The problem was that I defined ply inside of main(), instead of outside of the function.

dbush
2#
dbush Reply to 2017-12-04 19:33:04Z

You haven't actually defined ply globally:

int main(void) 
{ 
    int ply; 
    ply = 5; 
    printPly(); 
}

Here, ply is a local variable, not a global, since it is defined inside of a function. The extern line in your header file does not define the global, but declares it. It says "this variable exists somewhere", but it doesn't create it. Because there is no global defined, you get an undefined reference error.

Global variables must be defined at file scope, i.e. outside of a function:

int ply = 5;

int main(void) 
{ 
    printPly(); 
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.302119 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO