Global Variable Problem
-
-
I need to initialise the global variables, so when I attempt the following, an error message appears.Any suggestions appreciated in stdafx.cpp file #include "stdafx.h" int g_SomeGlobalVariable = 0; and in stdafx.h file extern int g_SomeGlobalVariable = 0;
Omit the "extern int g_SomeGlobalVariable" in the header file. You must use this "extern"-statement in the files from which you want to access your global variable (it's only for the linker). MS
-
Omit the "extern int g_SomeGlobalVariable" in the header file. You must use this "extern"-statement in the files from which you want to access your global variable (it's only for the linker). MS
You needn't to do that. Let the declaration in the
stdafx.h
(becausestdafx.h
is included in all source files generated by AppWizard), but omit the initialization (= 0
). Global and static variables must be initialized only in the source file. Robert-Antonio "Czech Railways discovered, that in case of disaster the most damaged wagons were the first and the last. So they decided to create trains without them." -
You needn't to do that. Let the declaration in the
stdafx.h
(becausestdafx.h
is included in all source files generated by AppWizard), but omit the initialization (= 0
). Global and static variables must be initialized only in the source file. Robert-Antonio "Czech Railways discovered, that in case of disaster the most damaged wagons were the first and the last. So they decided to create trains without them."I don't know if you are completely right. Certainly, you get an errormessage on an assignment in a header file. But in this case I wouldn't be amazed if the whole "extern"-statement is a problem, because his globalVar isn't "extern" in this case. I didn't try out. Anyhow, I wouldn't place an "extern"-statement in the stdafx.h, even because it is included everywhere else. But that's a question of the point of view. MS
-
I don't know if you are completely right. Certainly, you get an errormessage on an assignment in a header file. But in this case I wouldn't be amazed if the whole "extern"-statement is a problem, because his globalVar isn't "extern" in this case. I didn't try out. Anyhow, I wouldn't place an "extern"-statement in the stdafx.h, even because it is included everywhere else. But that's a question of the point of view. MS
-
Another way of doing the same would be declare it static. So in the stdafx.h you can write like static int gi_var = 0;
-
I don't know if you are completely right. Certainly, you get an errormessage on an assignment in a header file. But in this case I wouldn't be amazed if the whole "extern"-statement is a problem, because his globalVar isn't "extern" in this case. I didn't try out. Anyhow, I wouldn't place an "extern"-statement in the stdafx.h, even because it is included everywhere else. But that's a question of the point of view. MS