I probably dont understand how this externint foo works. I understand its like declaration but not definition so i tryed to define it inside main() like any normal variable int foo = 7; but yea .. this happened. Would be cool if somebody could explain this error to me
EDIT: i tryed to define foo inside my.cpp and than its worked. But in that case is there really a point from this extern inside of header file if i cant change its value anyway inside main. When is it usefull (extern) in practice?
#include "my.h"
int foo; // define foo as global
int main(){
foo = 7;
print_foo();
print(99);
}
I think i started to understand it.
In header file we declare that there will be variable called foo so we can start using it in functions that are declared in header file.
But still the question is why cant we define foo inside main(), we have to define it as a global variable only to make this work?
You use extern to declare that there is a global variable which is defined in another translation unit.
You put it in a header file for the same reason that you put anything in a header file - so that you can easily include a useful set of definitions and declarations in a number of different translation units, without having to copy and paste it.
Thank you man for explanation :)
Ill just tell how understood it
1st If we are making for example some math library we can declare externdouble pi; inside my_math_lib.h and than define it as double pi = 3.14...; inside my_math_lib.cpp. So now we can instantly start using this pi in any file we include this header file
2nd use as i understand could be to declare this extern variable externint foo; inside header file but not define it yet so we could start using this variable inside functions declared into the same header files like i did inside my print_foo() function