Originally Posted by
Jony
So, i'm reading about the Extern specifier and there's a couple of things i'm not quite getting and i thought maybe someone here could help me
The book i'm reading states that "we declare a global variable in file A, and then declare the variable again using the extern specifier in file B"
So, in file A i'd place
int i;
and in file B
extern int i; ??
Yes, that is the general idea. Though you should note that global variables are generally considered bad practice. Read this link: Global Variables Are Bad.
The most confusing part is "You can ignore the extern specifier, but include an
initializer, when you declare a global variable."
Ignoring the extern specifier and including an initializer means you are defining a global variable. There's a difference. Definition is where the variable is created and space is set aside for it. This should exist in exactly one .c file, and never in a header (.h) file. Declaration is simply stating the type of the variable, e.g. it's an int or float, char array, pointer to struct foo, etc. Declarations simply allow the compiler to check and make sure you're using that variable correctly.
so if i initialize a global variable like such
int i = 10;
does this mean i no longer need extern to make it visible on other source files?
No. If you put "int i = 10;" in all of your .c files, and never use extern, you end up with a separate variable for each .c file. Changing i in one file won't change it in any of the others. Your global variables will get out of sync.
"You should use the extern specifier (without an initializer) when you allude to a
global variable defined elsewhere."
Does this mean that i should not initialize the global variables but
rather make them extern and initialize them in the individual source files?
No. It means you define the variable once, in exactly one .c file, and declare it extern in every other .c file that needs to use that global variable. Normally, this is made easier by creating a header file that declares the extern symbols for you. Whether you initialize a global variable depends on whether you want it to have a specific value when the program starts, or just be zero (uninitialized globals are always set to zero).
Sorry if the question seems dumb... but, i'm kind of a noob so :P
Don't apologize. We were all there at one point, and you've done nothing wrong (other than use what sounds like a crappy book).
Here's a small example of how to use extern:
Code:
// foo.h
#ifndef foo_h__ // I'm an include guard! Use me in every header file. Read about me here: http://en.wikipedia.org/wiki/Include_guard
#define foo_h__
extern int foo;
#endif // foo_h__
// foo.c
int foo; // here is where I define the variable
// bar.c
#include "foo.h"
void bar(void)
{
printf("foo = %d\n", foo);
}