I am new to Xcode and when I build the following code (an MWE), I get the following error
ld: 3 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
I have three files as following;
main.cpp
#include "B.cpp"
int main() {
square(5);
return 0;
}
B.cpp
#include "A.cpp"
void square(int n){
display(n*n);
}
A.cpp
#include <iostream>
using namespace std;
void display(int num){
cout<<num;
}
I have tried different methods mentioned on stack overflow like change "Build Active Architecture Only" to "Yes" and some others but the error still persists.
Problem is that
main.cpp
has includedB.cpp
andA.cpp
. In your build process, you are also compilingB.cpp
andA.cpp
and trying to linkB.o
andA.o
alongwithmain.o
.Linking
B.o
andA.o
causes symbolsdisplay
andsquare
to be defined multiple times.display
is defined 3 times andsquare
defined 2 times.You just compile and build
main.cpp
. Do not buildA.cpp
andB.cpp
.Second way is that make
A.cpp
andB.cpp
toA.h
andB.h
and functionsinline
. So, they will be compiled only once.Third way, do not include
B.cpp
inmain.cpp
. Just put function declaration instead of inclusion.Generally, function declarations are put in header files. If that is required in multiple cases, make a header file.