views:

104

answers:

3

File 1:

static char* const path; //GLOBAL

int main()
{
   path = FunctionReturningPath();
   UsePath()
}

File 2:

extern char* const path; //GLOBAL from file 1

UsePath() //function using global
{
   something = path;
}

(Pseudo)

Would like to use path in file 2.
I'm defining the global within main in file 1, is that bad practice using a global?

and doesn't compile:

Compile Error: error LNK2001: unresolved external symbol _path

Any help is appreciated. Thank You.

+4  A: 

The static keyword at the file scope means make the variable specific to that compilation unit. Get rid of it.

David Gladfelter
(Nitpick, ignore if you (dis?)like) The proper term is "translation unit".
KennyTM
@KennyTM, thanks, I wonder where I (mis-)heard "compilation unit"?
David Gladfelter
@David, Java knows about compilation units
Johannes Schaub - litb
+6  A: 
static char* path; //GLOBAL

Wrong. making it static means it is local to the file, and cannot be exposed using extern. You want:

char* path; //GLOBAL
anon
+1  A: 

Remove the static keyword as it will make the symbol invisible to the linker.

In general, you should avoid global variables where you can. Instead, pass the variable as parameter where possible, or use a namespace (if you use C++). With global variables, you risk name clashes with external libraries, and the variable could be modified from anywhere.

AndiDog