Xcode linker command failed issue - c++

Ld /Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer- aeoygjukxhrzaxddvctkqcefsiql/Build/Products/Debug/NBAPlayer normal x86_64
cd /Users/noahheath/Documents/NBAPlayer
export MACOSX_DEPLOYMENT_TARGET=10.9
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -L/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Products/Debug -F/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Products/Debug -filelist /Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/NBAPlayer.LinkFileList -mmacosx-version-min=10.9 -stdlib=libc++ -Xlinker -dependency_info -Xlinker /Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/NBAPlayer_dependency_info.dat -o /Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Products/Debug/NBAPlayer
duplicate symbol __ZN9NFLplayerC1Ev in:
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/UnsortedStruct.o
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/main.o
duplicate symbol __ZN9NFLplayerC2Ev in:
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/UnsortedStruct.o
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/main.o
duplicate symbol __ZN9NFLplayer8ComparedES_ in:
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/UnsortedStruct.o
/Users/noahheath/Library/Developer/Xcode/DerivedData/NBAPlayer-aeoygjukxhrzaxddvctkqcefsiql/Build/Intermediates/NBAPlayer.build/Debug/NBAPlayer.build/Objects-normal/x86_64/main.o
ld: 3 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
This is the script I have received from xcode and I cannot find the error to save my life. Can someone help me debug this? Forgive me if this isn't presented in the correct format. This is my first time using this website.
Here is my main code and here is the unsorted struct class
#include "NFL.h"
class UnsortedStruct
{
public:
UnsortedStruct();
int GetLength() const;
bool IsFull() const;
void EmptyList();
void InsertItem(NFLplayer nflplayers);
void DeleteItem(NFLplayer nflplayers);
void ResetList();
NFLplayer GetItem(NFLplayer nflPlayers, bool& found);
NFLplayer GetNextItem();
private:
int length;
int currentPos;
NFLplayer NFLlist[MAX_PLAYERS];
};
#include <string>
using namespace std;
const int MAX_PLAYERS = 10;
enum RelationType1 {LESS1, GREATER1, EQUAL1};
struct NFLplayer//describes the set of information for a NFL player.
{
string position, school, name, team;
RelationType1 Compared(NFLplayer);
NFLplayer();
};
NFLplayer::NFLplayer()
{
position=" ";
school=" ";
name=" ";
team=" ";
}
RelationType1 NFLplayer::Compared(NFLplayer players)
{
if(name < players.name)
return LESS1;
else if(name > players.name)
return GREATER1;
else
return EQUAL1;
}

You declared your constructor and your Compared function inside the .h file. Move them into a .cpp file and things should run smoothly.
A more insight on what's happening :
.h files are copy pasted into every object that is being compiled . So the main.o and UnsortedStruct.o will have the header file copy-pasted inside their object at preprocessor time.
You have two objects, and in each object you define the ::Compared and ::NFLPlayer functions implementation. You end up with two implementations of the same function, hence the duplicate symbol.
The .h files are meant to provide definitions for to-be-used structures, classes, functions (it's a forward declaration so to speak).
Implementation bodies are implemented in .cpp files , which in turn will be compiled then linked throughout the code after compilation.
When you see implementations in .h files, you will see that these are inside the class definition :
Class A
{
void foo() { // do something };
}
This is valid, because that function will become inlined.
However, declaring void foo ,then implementing it as A::foo() in the same file will be troublesome if the file is included as header in multiple compile units (objects).

Lots of errors from derived data, I assume you did an upgrade of Xcode?
Do the following steps in Xcode:
Product --> (hold down Alt key) --> Clean Build Folder
Product --> Clean Project
Window --> Organizer --> Delete derived data
Then build your project again.

Related

Separate header file and its logic in c++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 5 years ago.
Please make me understand how header files works in C++. I am using osx and g++ compiler. I have
main.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
int main() {
square(10);
return 0;
}
myfunc.hpp
#ifndef MYFUNC_HPP_
#define MYFUNC_HPP_
/*
void square(int x) {
std::cout << x * x << std::endl;
};
*/
void square(int);
#endif // MYFUNC_HPP_
myfunc.cpp
#include<iostream>
#include "myfunc.hpp"
using namespace std;
void square(int x) {
cout << x * x << endl;
}
Now when I am trying to compile using g++ main.cpp , its giving
Undefined symbols for architecture x86_64:
"square(int)", referenced from:
_main in main-088331.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Because it is not able to find the function definition of square that is defined in myfunc.cpp.
But, if I defined square function in header file, it works because now it finds the function definition.
I want to use the function defined in myfunc.cpp in main.cpp, so I am using the header file myfunc.hpp. How can I achieve this? Am I doing something wrong here? Maybe my concept is not that clear about headers since I am new to C++ programming.
When you call g++ main.cpp, the compiler will try to compile and link the program, yet for linking, it lacks the source- or object file containing the definition of square. So it could compile main.cpp based on the function prototype given in the header file, yet it cannot link then.
To just compile main.cpp write
g++ -c main.cpp
To compile and link the complete program write:
g++ main.cpp myfunc.cpp
For more details concerning programs comprising several translation units confer, for example, this link.

Template inheritance in C++ and undefined symbols on Xcode

I have seen many related questions to this problem, but after carefully following advice from members, my problem still persists. The code is quite simple. I only have the following header file ("instrument.h"), which contains the base class and the template class:
#include <stdio.h>
#include <string>
using namespace std;
class Instrument
{
public:
Instrument();
virtual void print() const = 0;
};
template <class parameter> class Equity : public Instrument
{
public:
Equity();
virtual void print() const;
};
Now, in my main function on main.cpp I only do the following:
#include "instrument.h"
#include <iostream>
int main() {
Equity<double> pb;
return 0;
}
Well, I get the very well-known error:
Undefined symbols for architecture x86_64:
"Equity<double>::Equity()", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I have already changed in Build Settings the C++ standard library to libstdc++, also to default compiler, and so on. Do I have a problem with my project settings? Is perhaps the template wrongly implemented? I was thinking I should also have a instrument.cpp file, but then again definitions for templates must be kept in the header file so that would probably crash too.
Thanks in advance
You declared the default constructors for both Instrument and Equity but defined them nowhere.
Alter their definitions appropriately:
public:
Equity() = default; // Or {} in pre-C++11
// ^^^^^^^^^
(And equivalently for Instrument)
You can also completely omit the declarations of any default constructors for now since you didn't declare any other constructors in both Equity and Instrument and the default constructors will be generated automatically.

Compile errors with C++ static library include in Swift project

I created a static library that includes the follow C++ files:
//TestClass.h File:
#ifndef TESTCLASS_H_
#define TESTCLASS_H_
using namespace std;
#include <string>
class TestClass
{
public:
TestClass();
virtual ~TestClass();
int sum(int x, int y) const;
string chain(const string& x, const string& y) const;
};
#endif /* TESTCLASS_H_ */
//TestClass.cpp File:
#include<iostream>
#include "TestClass.h"
TestClass::TestClass()
{
}
TestClass::~TestClass()
{
}
int TestClass::sum(int x, int y) const
{
return x+y;
}
//Test.cpp File:
string TestClass::chain(const string& x, const string& y) const
{
return x+y;
}
int main(int argc, char* argv[])
{
TestClass test;
cout << "1+1 = " << test.sum(1,1) << endl;
cout << "Dog+Cat = " << test.chain("Dog","Cat") << endl;
return 0;
}
I added
-x objective-c++
flag in "Compile Source" and
-lstdc++
flag in "Info.plist Other Preprocessor flags".
When I link my just created static library (with Objective C wrapper files), I receive the 4 follow errors, that I don't have any idea how to fix it:
Undefined symbols for architecture arm64:
"vtable for __cxxabiv1::__class_type_info", referenced from:
typeinfo for TestClass in libPredictionComplete.a(TestClass.o)
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
"operator delete(void*)", referenced from:
TestClass::~TestClass() in libPredictionComplete.a(TestClass.o)
"___gxx_personality_v0", referenced from:
-[CppObject init] in libPredictionComplete.a(CppObject.o)
-[PredictionComplete init] in libPredictionComplete.a(PredictionComplete.o)
-[PredictionComplete chain::] in libPredictionComplete.a(PredictionComplete.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I'll appreciate any ideas about.
From my experience, Xcode will fail to link against C++ libraries when there are no C++ sources present in the top-level project. This is also true in pure Obj-C projects as well where you are linking against static libraries that have C++ code.
A less invasive solution is to simply include an empty C++ source file in your project (here's an example cpp stub) that is "compiled" into the final .app binary. It actually doesn't emit any code, but it makes Xcode aware that there is C++ code present, causing C++ libraries to be linked in.
The advantage of this solution is it avoids modifying the project settings in Xcode, so no need to add special linker flags to force Xcode to do the right thing.
I fixed it when I added the "-lstdc++" compile flag to "other linker flags" section in the Swift Project itself and not only in the static library project with c++ files.
The -lstdc++ should be in "Other Linker Flags" (or OTHER_LDFLAGS). Note that that will only work if the "C++ Standard Library" is set to libstdc++.
Also of note is that Xcode is usually smart enough to include the standard C++ library if the target has any C++ source code in it, so you don't need to explicitly link to either libstdc++ or libc++.
You should have -x c++ rather than objective-c++. There is, however, no need to specify this flag if you name your C++ sorce *.cpp.

Linking errors from MATLAB Mex library

I am having troubling compiling a MATLAB Mex library - specifically, the 'Correlation Clustering Optimization' code from this website.
I am trying to compile on an OSX machine, and am using the supplied mexall function. This runs the following line:
mex -O -largeArrayDims CXXFLAGS="\$CXXFLAGS -Wno-write-strings" QPBO.cpp QPBO_extra.cpp QPBO_maxflow.cpp QPBO_wrapper_mex.cpp QPBO_postprocessing.cpp -output QPBO_wrapper_mex
The error occurs at linking time with the following output to the MATLAB command line:
ld: duplicate symbol QPBO<int>::GetMaxEdgeNum() in QPBO_extra.o and QPBO.o
collect2: ld returned 1 exit status
mex: link of ' "QPBO_wrapper_mex.mexmaci64"' failed.
Judging from this, the function GetMaxEdgeNum is appearing in both QPBO_extra.o and QPBO.o. However, it is only actually defined in a header file, QPBO.h. I therefore suspect that both source files which include it are including it as a symbol in their object files, causing a problem at link time.
(Further information: Each source file also includes a file #include "instances.inc" at the very end of the file. instances.inc apparently seems to include some specific instantiations of the templated QPBO.)
Is there an obvious mistake I am making here? What can I do to increase my chances of being able to compile this code?
EDIT
This is the definition of the problematic GetMaxEdgeNum function in QPBO.h:
template <typename REAL>
inline int QPBO<REAL>::GetMaxEdgeNum()
{
return (int)(arc_max[0]-arcs[0])/2;
}
EDIT 2
Some more details about my machine:
OSX 10.6.8
MATLAB R2012a (also have R2011b)
g++ 4.2 or g++ 4.0 (or g++ 4.6 via MacPorts)
I've added some details on what I really want from an answer in my 'bounty description' below.
EDIT 3
There's a bit of consensus that instances.inc may be causing the trouble. This is included at the end of each cpp file, and it contains the following:
#include "QPBO.h"
#ifdef _MSC_VER
#pragma warning(disable: 4661)
#endif
// Instantiations
template class QPBO<int>;
template class QPBO<float>;
template class QPBO<double>;
template <>
inline void QPBO<int>::get_type_information(char*& type_name, char*& type_format)
{
type_name = "int";
type_format = "d";
}
template <>
inline void QPBO<float>::get_type_information(char*& type_name, char*& type_format)
{
type_name = "float";
type_format = "f";
}
template <>
inline void QPBO<double>::get_type_information(char*& type_name, char*& type_format)
{
type_name = "double";
type_format = "Lf";
}
It seems like the issue is that some template code is in .cpp files.
Remove the #include instances.inc declarations from the .cpp files.
Move all code from QPBO.cpp, QPBO_extra.cpp, QPBO_maxflow.cpp and QPBO_postprocessing.cpp to the header file qpbo.h.
You'll have now a single .cpp file qpbo_wrapper_mex.cpp and a single header qpbo.h
mex the file (in matlab) using:
>> mex -O -largeArrayDims qpbo_wrapper_mex.cpp
Should work...
Changing GetMaxEdgeNum to a static function, or putting it in an anonymous namespace will probably fix your problem.
The reason is, as you suggest, that it has external linkage in both object files, which results in a nameclash. My suggested solutions gives it internal linkage.
After edit:
Does it change anything if you define the method inside the class definition?
Like this:
template <typename REAL>
class QPB0 {
...
public:
inline int GetMaxEdgeNum()
{
return (int)(arc_max[0]-arcs[0])/2;
}
...
};

Undefined symbols for architecture i386:

I've recently moved over to a mac, and am struggling using the command line compilers. I'm using g++ to compile, and this builds a single source file fine. if I try to add a custom header file, when I try to compile using g++ I get undefined symbols for architecture i386. The programs compile fine in xCode however. Am I missing something obvious?
tried using g++ -m32 main.cpp... didn't know what else to try.
Okay, The old code compiled... Have narrowed it down to my constructors.
class Matrix{
public:
int a;
int deter;
Matrix();
int det();
};
#include "matrix.h"
Matrix::Matrix(){
a = 0;
deter = 0;
}
int Matrix::det(){
return 0;
}
my error is
Undefined symbols for architecture x86_64:
"Matrix::Matrix()", referenced from:
_main in ccBWK2wB.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
my main code has
#include "matrix.h"
int main(){
Matrix m;
return 0;
}
along with the usual
It looks like you’ve got three files:
matrix.h, a header file that declares the Matrix class;
matrix.cpp, a source file that implements Matrix methods;
main.cpp, a source file that defines main() and uses the Matrix class.
In order to produce an executable with all symbols, you need to compile both .cpp files and link them together.
An easy way to do this is to specify them both in your g++ or clang++ invocation. For instance:
clang++ matrix.cpp main.cpp -o programName
or, if you prefer to use g++ — which Apple haven’t updated in a while, and it looks like they won’t in the foreseeable future:
g++ matrix.cpp main.cpp -o programName
is not the case here, but it may happen to be the you forget to put the class name with ::
for example:
a good format:
foo.h
class Foo{
public:
Foo();
void say();
private:
int x;
};
foo.cpp
Foo::Foo(){
this->x = 1;
}
void Foo::say(){
printf("I said!\n");
}
a bad format
foo.h
class Foo{
public:
Foo();
void say();
private:
int x;
}
foo.cpp
Foo::Foo(){
this->x = 1;
}
//I always mistake here because I forget to put the class name with :: and the xcode don't show this error.
void say(){
printf("I said!\n");
}
Did you actually define the Box constructor somewhere? (like Line.cpp)