Considering the example below:
header.h
extern int somevariable;
void somefunction();
source.cpp
#include "header.h"
somevariable = 0; // this declaration has no storage class or type specifier
void somefunction(){
somevariable = 0; // works fine
}
I couldn't find the answer to the following questions:
Why can't I just forward declare
int somevariable
and initialize it in the.cpp
file?Why is the
somefunction()
function able to "see"somevariable
when declared usingextern int somevariable
, and why is it not accessible outside of a function?
CodePudding user response:
extern int somevariable;
means definition of somevariable
is located somewhere else. It is not forward declaration. Forward declaration is used in context of classes and structs.
somevariable = 0;
is invalid since this is assignment and you can't run arbitrary code in global scope.
It should be:
int somevariable = 0;
and this means define (instantiate) global variable somevariable
in this translation unit and initialize it to 0
.
Without this statement linking of your program will fail with error something like: undefined reference to 'somevariable' referenced by ...
.
Use of global variable in any langue is considered as bad practice, sine as project grows global variable makes code impossible to maintain and bug-prone.