Here is a practical explanation.
Suppose you had the following incl.h file:
#ifndef INCL_H
#define INCL_H
int x = 10;
#endif
#ifndef INCL_H
#define INCL_H
int x = 10;
#endif
To copy to clipboard, switch view to plain text mode
And then you had a file a.cpp such as this:
#include "incl.h"
int func1() { return x; }
#include "incl.h"
int func1() { return x; }
To copy to clipboard, switch view to plain text mode
and another one, b.cpp, such as this:
#include "incl.h"
int func2() { return (x+1); }
#include "incl.h"
int func2() { return (x+1); }
To copy to clipboard, switch view to plain text mode
Now suppose you have some other piece of code that contains:
int x1 = func1();
int x2 = func2();
int x1 = func1();
int x2 = func2();
To copy to clipboard, switch view to plain text mode
When the compiler compiles a.cpp into a.o, it includes the incl.h file which declares a "x" variable and func1() can see the variable and operate on it.
Now when the compiler compiles b.cpp into b.o, it includes the incl.h file which also declares a "x" variable and func2() can see it and operate on it.
Now the linker tries to consolidate modules of your program into a single executable. It looks at a.o and sees it has a declaration of variable "x". But b.o also has a declaration of variable "x". To the compiler those are two different variables and it can't cope with such a situation and returns an error. Why? What if it didn't, that's the same variable isn't it? Ok, but what if a.cpp declared x as an integer with value "11" and b.cpp declared it with value "-1"? What would the values of x1 and x2 be after the last snippet?
What "extern" does is that it says "somewhere out there there is a variable called x". There is no declaration here, just an info for the preprocessor and compiler that "x" is a valid integer variable. It means you have to declare this variable somewhere and that's what you do in your "nsclass.cpp". Then the compiler sees only one "x" variable and two "placeholders" for an x variable. There is no conflict and linking can succeed.
Bookmarks