简体   繁体   中英

Xcode: linker command failed with exit code 1 (use -v to see invocation) [C++]

I am running a c++ programs with multiple files (2)

goofing_around.cpp

add.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:

#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. Super weird,but does anyone know why?

The problem is that you are not linking well the add method. You have implemented it in add.cpp but you don't add the link to it in the main code. You should include another "include" in goofing_around.cpp, something like

#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). If not, there no sense to write that since you can just link your main code to the add.cpp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM