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 somevariableand initialize it in the.cppfile?Why is the
somefunction()function able to "see"somevariablewhen declared usingextern int somevariable, and why is it not accessible outside of a function?
extern int somevariable;says to look elsewhere for a definition ofsomevariable,somevariable = 0;assigns a value of0to it, but in neither case have you actually provided a definition. If you want the definition to reside in the cpp file, the line would beint somevariable;, orint somevariable = 0;if you want to define and initialize it together.int somevariable = 0;