Click here to Skip to main content
12,999,157 members (41,900 online)
Rate this:
Please Sign up or sign in to vote.
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 21-Mar-13 23:50pm
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.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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

#pragma once

This is better as like former:

#ifndef _BLAH_
#define _BLAH_
#endif // _BLAH_ 
shanmugarajaa 22-Mar-13 6:44am
I did the same what you are cite above.

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

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?
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.

//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


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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170622.1 | Last Updated 22 Mar 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100