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.
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
The static keyword at the file scope means make the variable specific to that compilation unit. Get rid of it.
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.
精彩评论