| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
regarding global object access in multiple file
Dear friends,
i write a class in header file. then i made aglobal object of this class in header file. when i use this in one source file, my program works perfactly, but when i use this in two different source file, iget some linking error(error LNK2005: "class myclass test1" (?test1@@3Vmyclass@@A) already defined in globaltest.obj) i am pesting my three file here, Please give me some tips to correct this. I want to use global object in multiple file. header file(globaltest.h) #include <iostream> class myclass { public: char * name; int rollno; myclass(); public: void setname(char* tname,int tno); int getrollno(); char* getname(); }; myclass test1; first source file #include "globaltest.h" void main() { char* lname = "nilesh"; int lrollno = 5; test1.setname(lname,lrollno); lrollno= test1.getrollno(); lname = test1.getname(); } void myclass::setname(char* tname,int tno) { name = tname; rollno = tno; } int myclass::getrollno() { return rollno; } char* myclass::getname() { name = "vinod"; return name; } myclass::myclass(){} second source file #include"globaltest.h" void secondcall() { int trollno = 8; char *tname = "ajit"; //test1.setname(tname,trollno); trollno = test1.getrollno(); tname = test1.getname(); } Please provide me right tips. Thanks, Vinod |
|
#2
|
|||
|
|||
|
In second source file, where are you defining test1.getrollno() and test1.getname()?
|
|
#3
|
|||
|
|||
|
move
myclass test1; from your include file into your main file. It will need to be in the global section (ie outside of any brackets). Then define it as external in your second program file. The compiler is trying to create two copies of this. One in your first program file (main) and one in your second program file. As an alteranative, you might be able to get around this be creating a namespace in your include file and then use that namespace in both your first and second program file, but I'm not sure this will create only one instance of test1. Look up compiler directives in your book and see if there is a way you can get the compiler to only create one instace of test1. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > regarding global object access in multiple file |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|