954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Multiple declaration error during linking

Hello,

I am stuck with a multiple declaration error during linking.
I have 4 C++ source and corresponding header files(A, B, C,D) and one main source file(Main.cpp).
Apart from that, I have one header file which contains two function declarations and some #define constants (Config.h) and 2 array decl which are used in the functions itself.
I have #included the he Config.h in Main.cpp, A.h, B.h, C.h.
I have also #included A.h in Main.cpp
Actually, I am using one function from Config.h in Main.cpp and another function in A.cpp.
Now, in this situation I have compiled all the source files separately.
When I am trying to create the exec, during linking of A.o, B.o, C.o, D.o and Main.o...I get error of multiple definition of functions and array declarations.

Please suggest to overcome this error!!!

abhishek2301
Light Poster
27 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

Put only function prototypes and extern object declarations in header files, such as

// A.h file
extern void foo();
extern int f1;


Now, in one and only one *.cpp file you have to declare the same without theextern keyword.

// A.cpp file
#include "A.h"

int f1 = 0;

void foo()
{

}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Thanks for you reply!!!

But, suppose if I want to keep the array decl and the function implementations in Config.h and I use one function from Config.h in Main.cpp and another function from Config.h in A.cpp.

How to do this way???

Please help!!!

abhishek2301
Light Poster
27 posts since Nov 2007
Reputation Points: 10
Solved Threads: 0
 

>>How to do this way???
You don't! Function implementations can not be put in header files for the reason you have already discovered -- duplicate definition errors.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You