When you declare a variable inside a source file it is in global scope, just like declaring it in a header file. I'm not sure you are entirely understanding what is going on here, so I'll give you an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// Header.hpp
#ifndef __HEADER_HPP_INCLUDED__
#define __HEADER_HPP_INCLUDED__
int val;
void doSomething();
#endif // __HEADER_HPP_INCLUDED__
// dosomething.cpp
#include "Header.hpp"
void doSomething() {
val = 5;
}
// main.cpp
#include "Header.hpp"
#include <iostream>
int main() {
doSomething();
std::cout << val;
return 0;
}
|
In this example, you will get an error. This is because all the contents of
Header.hpp is just copied straight into the source files, so two copies of 'val' will have been declared: one for 'main.cpp' and one for 'dosomething.cpp'. This is because neither know of the existance of the other value. One way to fix this would be to declare val as
extern, saying it is outside that particular source file. If we take what the compiler sees, the two source files would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// dosomething.cpp
void doSomething();
extern int val;
void doSomething() {
val = 5;
}
// main.cpp
void doSomething();
extern int val;
/* contents of <iostream> are here */
int main() {
doSomething();
std::cout << val;
return 0;
}
|
Now, you'll get a different error: Because declaring val
extern doesn't actually declare the variable, you have told the linker of the existance of a variable that doesn't actually exist. Therefore, our final program should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
// Header.hpp
#ifndef __HEADER_HPP_INCLUDED__
#define __HEADER_HPP_INCLUDED__
void doSomething();
extern int val;
#endif // __HEADER_HPP_INCLUDED__
// doSomething.cpp
#include "Header.hpp"
int val; // declaring 'val' so it exists somewhere
void doSomething() {
val = 5;
}
// main.cpp
#include "Header.hpp"
#include <iostream>
// don't define 'val' here: otherwise we get our original problem again!
int main() {
doSomething();
std::cout << val;
return 0;
}
|
Now, if you are only using one source file, this problem wouldn't have occurred. However, it is good to get into the practice of doing things like this with global variables declared in header files, so that you don't add in another source file and suddenly find everything has broken.