Reputation: 1079
My main.cpp includes the header file setup.h.
setup.h reads data from a file, which is then used in main.cpp.
In the data file which setup.h reads, one piece of data is a single float variable, which I need to use in a function (from another header file) in main.cpp.
I can't use extern when defining the variable in my header file, because then I can't initialize it with the data from the file (gives an error when compiling):
setup.h
...
extern float G = 0;
input >> G;
...
main.cpp
...
float G;
instance function(G);
...
How do I get the initialized variable in my main.cpp file?
Upvotes: 0
Views: 1423
Reputation: 35164
When you include a file using #include
-directive, then you can think as if the content of the included file were inserted directly at the place of the #include
-statement.
That means that the content of the header file is not compiled on its own but in the course of the translation unit where it is included (and in the context of the place where it is included).
So your code would probably lead to...
extern float G = 0;
input >> G;
float G;
which has several issues then.
First, variable G
is defined twice; Note that extern
together with an initializer does not just declare but actually define a variable (despite the extern
-keyword).
Second, statement input >> G
is probably used at file scope, where it is not allowed (such code has to be placed inside a function).
So you the only thing you could do is...
setup.h
extern float G; // no initialisation here
setup.cpp
float init() {
float dummy;
cin >> dummy;
return dummy;
}
float G = init(); // definition and initialization through a function
main.cpp
#include "setup.h"
int main() {
cout << G; // use of (initialized, externally defined) G
}
Upvotes: 1
Reputation: 73607
In the header you should just declare the variable so that the compiler knows that it exists somewhere:
extern float G;
In one of the compilation unit (cpp) you have to define the variable. You can then initalize it:
float G = 0.0;
Don't abuse of global variables ;-)
Upvotes: 4