Click here to Skip to main content
15,904,926 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friend,
I have facing the problem of "Already defined .obj". My console application consist of:
Lib.cpp, Lib.h, Pwrcom.h and global.cpp files. I have been included Pwrcom.h header in Lib.ccp and global.cpp files and also included Lib.h header in the global.ccp as well.

For Example:
Lib.cpp file
#include "Pwrcom.h"
#include "Lib.h"

-----------
---------

global.cpp file
#include "Pwrcom.h"
#include "Lib.h"

--------------------
-----------------

This Pwrcom.h consist of all global variable declaration. After I refered different forum and technical site, I come know that, Pwrcom.h used several times.. If I have remove "pwrcom.h" header file from global.cpp or else from Lib.cpp, compiler give out error report. Because those global variable has been used both the files "Global.cpp" and "Lib.cpp".
Kindly help me to fix this problem.

Thanks and Regards,
S.Shanmuga Raja
Posted
Comments
Richard MacCutchan 22-Mar-13 7:38am    
You should look at your design. The use of global variables is generally unnecessary and should be avoided. you have fallen into the first trap that this design pattern may cause.

Try to use following statement in every header file you write to be sure including the header file only once:

C++
#pragma once


This is better as like former:

C++
#ifndef _BLAH_
#define _BLAH_

#endif // _BLAH_ 
 
Share this answer
 
v2
Comments
shanmugarajaa 22-Mar-13 6:44am    
Hi,
I did the same what you are cite above.

Lib.ccp file
pragma once
#include "pwrcom.h"
#include "Lib.h"

Global.cpp
pragma once
#include "pwrcom.h"
#include "Lib.h"

But still i getting error..
Maxim Kartavenkov 22-Mar-13 8:13am    
#pragma once - should be in .h file - had you seen example in my solution?
You should declare variables in .h files but initialize them in .cpp file.
Otherwise you include header 2 times and then it is initialize 2 times.
Note: do not forget to use #pragma once or via definition avoid doublbe declaration.

C++
//example: .h

#pragma once
// declare variable so compiler will know 
// that it will be initialized sometehre
extern int g_variable;

//example .cpp
// initialize variable
// we should initialize it as you will linker error unresolved symbol as 
// variable marked as extern
int g_variable = 0;

// in any other files there you include header you will not get the linker error


Maxim.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900