[英]Xcode: linker command failed with exit code 1 (use -v to see invocation) [C++]
I am running a c++ programs with multiple files (2) 我正在运行包含多个文件的C ++程序(2)
goofing_around.cpp goofing_around.cpp
add.cpp add.cpp
goofing_around.cpp: goofing_around.cpp:
//
// goofing_around.cpp
// new
//
// Created by Chirag Maheshwari on 14/08/18.
// Copyright © 2018 Chirag Maheshwari. All rights reserved.
//
#include <iostream>
int add(int x,int y);
int doubleNumber(int n)
{
return 2*n ;
}
int main()
{
int x;
std::cout << "Enter the number to be doubled: ";
std::cin >> x;
std::cout << doubleNumber(x)<<std::endl;
std::cout << add(3,2) << std::endl;
return 0;
}
add.cpp: add.cpp:
#include <iostream>
int add(int x,int y){
return x+y;
}
And yet I get an error which goes like this: 但是我得到了这样的错误:
duplicate symbol _main in:
/Users/chirag/Library/Developer/Xcode/DerivedData/new-hapneuayvrpdonefrpnervwkxysx/Build/Intermediates.noindex/new.build/Debug/new.build/Objects-normal/x86_64/goofing_around-5915963FFFEE024.o
/Users/chirag/Library/Developer/Xcode/DerivedData/new-hapneuayvrpdonefrpnervwkxysx/Build/Intermediates.noindex/new.build/Debug/new.build/Objects-normal/x86_64/goofing_around-93C433489854664D.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Edit: This was weird.The error was there even before I added the add.cpp file.But then I deleted the projects and tried again.And after rewriting all the code,and adding the add file,I deleted the .h file.But only this time it worked,with the exact same code,and including the same function prototype.I did not have to include the add.cpp files either. 编辑:这很奇怪。错误甚至在我添加add.cpp文件之前就存在。但是随后我删除了项目并再次尝试。重写所有代码并添加添加文件之后,我删除了.h文件。但是只有这次,它可以使用完全相同的代码运行,并且包含相同的函数原型。我也不必包含add.cpp文件。 Super weird,but does anyone know why? 超级奇怪,但是有人知道为什么吗?
The problem is that you are not linking well the add method. 问题是您没有很好地链接add方法。 You have implemented it in add.cpp but you don't add the link to it in the main code. 您已经在add.cpp中实现了它,但是没有在主代码中添加指向它的链接。 You should include another "include" in goofing_around.cpp, something like 您应该在goofing_around.cpp中添加另一个“包含”,例如
#include "add.cpp";
It should work. 它应该工作。
Another observation: there is no need to print the name of the method "add" in the main code, since these things are done in the header files (if you have any). 另一个观察结果:不需要在主代码中打印方法“ add”的名称,因为这些操作都是在头文件中完成的(如果有的话)。 If not, there no sense to write that since you can just link your main code to the add.cpp. 如果没有,那是没有意义的,因为您可以将主代码链接到add.cpp。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.