Xcode C++ :: Duplicate Symbols for Architecture x86_64
Solution 1
Problem is that main.cpp
has included B.cpp
and A.cpp
. In your build process, you are also compiling B.cpp
and A.cpp
and trying to link B.o
and A.o
alongwith main.o
.
Linking B.o
and A.o
causes symbols display
and square
to be defined multiple times. display
is defined 3 times and square
defined 2 times.
You just compile and build main.cpp
. Do not build A.cpp
and B.cpp
.
Second way is that make A.cpp
and B.cpp
to A.h
and B.h
and functions inline
. So, they will be compiled only once.
Third way, do not include B.cpp
in main.cpp
. Just put function declaration instead of inclusion.
//main.cpp
void square(int);
int main() {
square(5);
return 0;
}
Generally, function declarations are put in header files. If that is required in multiple cases, make a header file.
Solution 2
For me, changing 'No Common Blocks' from Yes to No ( under Targets->Build Settings->Apple LLVM - Code Generation ) fixed the problem.
Ahmad
Updated on July 09, 2022Comments
-
Ahmad almost 2 years
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.
-
Ahmad over 9 yearsThanks for the suggestion, I have tried in the following manner but the error still persists. 1. Clean the Project. 2. Select "Main.cpp" 3. Product -> Perform Action -> Compile "Main.cpp" 4. Repeated Step 3, for "A.cpp" and "B.cpp" 5. Run the Project. 6. Got the same error. I also tried to compile only "Main.cpp" and then run but XCode build the complete project.<br/> Can you please elaborate how to compile and build "Main.cpp" independently. P.S. I am using XCode 6.1.1
-
WhozCraig over 9 years@Ahmad you're still not getting it. You're including the same source in two different translation units. The code in
A.cpp
is compiled as a single translation unit toA.o
, then the same code is#include
-ed intomain.cpp
(which is the real problem). The second option in this answer is ideal. Do that. -
Ahmad over 9 years@WhozCraig Thank you. I used the second option, which solved the problem.
-
Christopher Connery over 4 yearsThank you! I used the first solution, this solved my problem
-
explorer almost 4 yearsNicely explained! Thanks a lot. I have been suffering by this issue for past 2 days.