Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode C++ :: Duplicate Symbols for Architecture x86_64

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.

like image 629
Ahmad Avatar asked Dec 12 '14 04:12

Ahmad


People also ask

What does 1 duplicate symbol for architecture x86_64 mean?

duplicate symbol _OBJC_IVAR_$_BLoginViewController._hud in: 17 duplicate symbols for architecture x86_64. "Means that you have loaded same functions twice. As the issue disappear after removing -ObjC from Other Linker Flags, this means that this option result that functions loads twice:"

What is undefined symbols for architecture x86_64?

Why Is the Undefined Symbols for Architecture x86_64: Error Happening? This error is happening due to the lack of included values inside the declared statements in your code. The browser is going to render the information incorrectly and show this error, especially if you are working with Main and Similarity tools.


2 Answers

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.

like image 154
doptimusprime Avatar answered Oct 15 '22 04:10

doptimusprime


For me, changing 'No Common Blocks' from Yes to No ( under Targets->Build Settings->Apple LLVM - Code Generation ) fixed the problem.

enter image description here

like image 30
Mitesh Khatri Avatar answered Oct 15 '22 03:10

Mitesh Khatri