Defining a constant datamember

Programe #1

// file.h
1
2
3
4
5
class File
{
public:
static const int var = 9;
};

-

// main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "file.h"
using namespace std;

int main() {
File f;
cout << f.var;
return 0;
}

Programe #2

// file.h
1
2
3
4
5
6
7
int Globalvar ;
class File
{
public:
static const int var = 9;
};
-


// main.cpp
1
2
3
4
5
6
7
8
9
10
extern int GlobalVar;

#include <iostream>
#include "file.h"
using namespace std;

int main() {
cout << GlobalVar;
return 0 ;
}

Program#1 is running fine, but program#2 gives linker error:

error LNK2005: "int GlobalVar" (?x@@3HA) already defined in file.obj
I know the header files are never compiled. Then in the above case, how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar? What is the difference between this two programs?
> already defined in file.obj
¿do you have a `file.cpp' ?

> not able to find the definition of GlobalVar?
It does find its declaration. Several times.
In both the programe we have defined variables . In programe#1 we have difined static constant while in programe#2 we have defined GlobalVar .
i want to know why programe#1 is working fine where as programe#2 doesnot .
> i want to know why programe#1 is working fine where as programe#2 doesnot .

File::var has internal linkage; it can be defined once per translation unit.

::GlobalVar has external linkage. It can be defined only once in the entire program.

One Definition Rule:
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=386
http://en.wikipedia.org/wiki/One_Definition_Rule
Topic archived. No new replies allowed.