Function Overloading problem in Separate Files
I’ve been working on a small program that I need to separate the operation functions from the implementation file for a little of proprietary issue. I had an function overloaded in my operation file.
Below is just a sample code that will generate the same error from the program that I’m working :
This is the operation functions. Filename operationfunctions.cpp
// Functions Prototype
void funcOverload ( int );
void funcOverload ( double );
// Functions Definition
template<typename T>
void funcTemplate ( T value )
{
cout<<”TESTING FUNCTION TEMPLATE”<<endl;
cout<<”value pass “<<value<<endl;
}
void funcOverload ( int intValue )
{
cout<<”TESTING FUNCTION OVERLOADING”<<endl;
cout<<”value pass “<<intValue<<endl;
}
void funcOverload ( double doubleValue )
{
cout<<”TESTING FUNCTION OVERLOADING”<<endl;
cout<<”value pass “<<doubleValue<<endl;
}
This is the implementation file or the main. Filename is implementation.cpp.
#include <iostream>
#include "test_templates.cpp"
using namespace std;
int main ( int argc, char **argv )
{
int myInt = 10;
double myDouble = 2.4;
// Testing for function overloading
cout<<”Integer Data type call”<<endl;
funcOverload (myInt);
cout<<”Double Data type call”<<endl;
funcOverload (myDouble);
// End of testing for function overloading
return 0;
}
As I run the code an error LNK occurs. Below is the error.
operationfunctions.obj : error LNK2005: "void __cdecl funcOverload(int)" (?funcOverload@@YAXH@Z) already defined in implementation.obj
The problem in here is that the object funcOverload has already been built or it has already exist in the implementation object. Since the funcOverload(int) was the first one being called then that function was the first one that exist in the implementation object.
The solution that I’d come up is to use inline functions for the overloaded functions. I come up with this idea because as I observed when I mixed up the code in one file, everything works fine. That’s why I use inline to make the two overloaded functions exist as if they are just in the same file.
Solution :
// Functions Prototype
void funcOverload ( int );
void funcOverload ( double );
// Functions Definition
template<typename T>
void funcTemplate ( T value )
{
cout<<”TESTING FUNCTION TEMPLATE”<<endl;
cout<<”value pass “<<value<<endl;
}
inline void funcOverload ( int intValue )
{
cout<<”TESTING FUNCTION OVERLOADING”<<endl;
cout<<”value pass “<<intValue<<endl;
}
inline void funcOverload ( double doubleValue )
{
cout<<”TESTING FUNCTION OVERLOADING”<<endl;
cout<<”value pass “<<doubleValue<<endl;
}
