14

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
  • 163
  • 1
  • 2
  • 9

2 Answers2

25

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.

doptimusprime
  • 9,115
  • 6
  • 52
  • 90
  • Thanks 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.
    Can you please elaborate how to compile and build "Main.cpp" independently. P.S. I am using XCode 6.1.1
    – Ahmad Dec 12 '14 at 05:18
  • @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 to `A.o`, then the *same code* is `#include`-ed into `main.cpp` (which is the **real** problem). The second option in this answer is ideal. Do that. – WhozCraig Dec 12 '14 at 05:52
  • @WhozCraig Thank you. I used the second option, which solved the problem. – Ahmad Dec 12 '14 at 06:14
  • Thank you! I used the first solution, this solved my problem – Mira Welner Aug 23 '19 at 02:10
  • 1
    Nicely explained! Thanks a lot. I have been suffering by this issue for past 2 days. – explorer Jun 16 '20 at 23:15
2

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

Mitesh Khatri
  • 3,935
  • 4
  • 44
  • 67