So, I have a variable declared globally. For it to be used, it has to be defined. I get different results based on whether I define it globally or within scope of the main function.
Here's the basic code:
// main.cpp
//int variable = 3;
int main()
{
//int variable = 5;
func();
return variable;
}
// source.cpp
#include "source.hpp"
void func()
{
cout << variable << endl;
}
// source.hpp
#ifndef __SOURCE_HPP_INCLUDED__
#define __SOURCE_HPP_INCLUDED__
#include<iostream>
using namespace std;
extern int variable;
void func();
#endif // __SOURCE_HPP_INCLUDED__
So, if I define globally (outside main), then everything works. But if I define within main, then I get "undefined reference to 'variable'" errors. But I only call upon source.cpp when I'm inside main; so why do I get this error, if variable is defined within the same "scope" as func? Is it the compiler just preemptively giving the error before linking is done? Or is it related to the fact that I declared it as "extern"?
You can't define a global variable inside a function. You're actually defining a different, unrelated local variable that just happens to have the same name.
func
references the global variable, so you must have a definition for it.