Xcode C ++ :: Architecture x86_64的重复符号 [英] Xcode C++ :: Duplicate Symbols for Architecture x86_64
问题描述
我是Xcode的新手,当我构建下面的代码(一个MWE),我得到以下错误
I am new to Xcode and when I build the following code (an MWE), I get the following error
ld:3架构的重复符号x86_64
clang:error:linker命令失败,退出代码1(使用-v查看调用)
ld: 3 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
我有三个文件如下:
main.cpp
main.cpp
#include "B.cpp"
int main() {
square(5);
return 0;
}
B.cpp
B.cpp
#include "A.cpp"
void square(int n){
display(n*n);
}
A.cpp
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.
推荐答案
问题是 cpp
已包含 B.cpp
和 A.cpp
。在您的构建过程中,您还要编译 B.cpp
和 A.cpp
并尝试链接 Bo
和 Ao
以及 main.o
。
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
.
链接 Bo
和 Ao
会导致符号显示
和 square
多次定义。 display
定义3次,正方形
定义2次。
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.
你只需编译并构建 main.cpp
。不要构建 A.cpp
和 B.cpp
。
You just compile and build main.cpp
. Do not build A.cpp
and B.cpp
.
第二种方式是让 A.cpp
和 B.cpp
到 Ah
和 Bh
和函数 inline
。
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.
第三种方式,不要包含 B.cpp
在 main.cpp
。只要放入函数声明,而不是包含。
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.
这篇关于Xcode C ++ :: Architecture x86_64的重复符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!