I declare a Algebra.h
file which holds the declaration of an add()
function:
#ifndef Algebra_
#define Algebra_
namespace Algebra{
int add(int x, int y);
}
#endif
Then I implement add()
as:
Algebra.cpp
#include "Algebra.h"
namespace Algebra{
int add(int x, int y){
return x+y;
}
}
Then I have classes A and B, which include Algebra.h
:
B.h
#ifndef B_
#define B_
#include "Algebra.h"
#include <iostream>
class B{
public:
void func(int x, int y);
};
#endif
B.cpp
#include "B.h"
void B::func(int x, int y){
int val = Algebra::add(x,y);
std::cout << "B : "<< val << std::endl;
}
A.h
#ifndef A_
#define A_
#include <iostream>
#include "Algebra.h"
#include "B.h"
class A{
public:
void func(int x, int y);
};
#endif
A.cpp
#include "A.h"
void A::func(int x, int y){
int val = Algebra::add(x,y);
std::cout << "A : " << val << std::endl;
}
main.cpp
#include "A.h"
#include "B.h"
#include "Algebra.h"
int main(){
A a;
B b;
a.func(3,4);
b.func(3,4);
int val = Algebra::add(3,4);
std::cout << "main : " << val << std::endl;
}
I tried compilation using
g++ A.cpp B.cpp main.cpp -o bin
g++ A.cpp B.cpp Algebra.cpp main.cpp -o bin
I get this error:
/tmp/ccBXhev4.o: In function 'Algebra::add(int, int)': main.cpp:(.text+0x0): multiple definition of 'Algebra::add(int, int)' /tmp/ccfaCF5H.o:A.cpp:(.text+0x0): first defined here collect2: error: ld returned 1 exit status
I even tried inlining the add()
function in Algebra
, but still get the error. Also I don't want to make Algebra be a class.
Why am I getting a multiple definition error even though I am adding the Algebra header file, and it does not define but only declare?
inline int add( int x, int y){ return x+y; }
– Thomas Apr 24 '18 at 18:27<iostream>
andAlgebra.h
should be moved fromA.h
andB.h
toA.cpp
andB.cpp
, since they are not actually used in the.h
files but only in the.cpp
files. AndB.h
should be removed fromA.h
sinceB
is not used byA
. And<iostream>
should be added tomain.cpp
. Use headers explicitly, only where they are actually needed, do not rely on headers being included implicitly, and do not include headers you do not need. – Remy Lebeau Apr 24 '18 at 19:32