-
December 21st, 2012, 10:26 AM
#1
Defining a constant datamember
Programe #1
// file.h
class File
{
public:
static const int var = 9;
};
-
// main.cpp
#include <iostream>
#include "file.h"
using namespace std;
int main() {
File f;
cout << f.var;
return 0;
}
Programe #2
// file.h
int Globalvar ;
class File
{
public:
static const int var = 9;
};
-
// main.cpp
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?
-
December 21st, 2012, 10:57 AM
#2
Re: Defining a constant datamember
Originally Posted by vikuseth
how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar?
The compiler/linker was able to find the definition of GlobalVar. In fact, it found the definition at least twice: once in main.cpp, and another time in say, file.cpp. Hence the error message stated that the variable was "already defined in file.obj".
The solution is to define the variable in exactly one source file, and then put that extern declaration in the header instead.
In the case of the static const member variable, it is a special exception that you can initialise such a variable in the class definition if it is of an integer type. Otherwise, you should place the initialisation in exactly one source file.
-
December 21st, 2012, 11:24 AM
#3
Re: Defining a constant datamember
so shall i take like if it is a static const integral type of data then it can be defined inside .h file . It will not show any linker error . But for others it will show one error . Is it what you are saying ?
-
December 21st, 2012, 11:36 AM
#4
Re: Defining a constant datamember
Yes, that is the gist of what you're asking about, I think.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|