Undefined symbols for architecture i386: - c++

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)

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.

Xcode linker command failed issue

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.

C++: Linking files with GCC compiler

I have three files : myh.h; my.cpp; use.cpp. Here are the contents of the files:
myh.h
extern int foo;
void print_foo();
void print(int);
my.cpp
#include "myh.h"
#include <iostream>
void print_foo()
{
std::cout<<foo<<std::endl;
}
void print(int i)
{
std::cout<<i<<std::endl;
}
use.cpp
#include "myh.h"
int main()
{
foo=7;
print_foo();
print(99);
return 0;
}
GCC spews out the following error:
my.o:my.cpp:(.text+0x7): undefined reference to `foo'
use.o:use.cpp:(.text+0x10): undefined reference to `foo'
collect2: ld returned 1 exit status
I compile the files using the -c command and it doesn't give errors. I link using the following command:
g++ -o final my.o use.o
What is the problem here, I read other topics with similar problems, and the case here is just strange .....
For the curious this is an exercise drill from Stroustrup's book Programming principles of using C++
Edit: I did as dasblinkenlight said, and in use.cpp I added an int in front of foo (so now foo is defined), but I still get this error:
my.o:my.cpp:(.text+0x7): undefined reference to `foo'
collect2: ld returned 1 exit status
Which tells me that it is not defined in my.cpp also? If I have to define it everywhere what is the point of including it in the header file, or how should this be approached more appropriately?
You get a linker error because you declared foo, but you never defined it.
extern int foo is only a declaration; it does not cause allocation of memory for the foo variable, only promises that you will do it at some other place. To fix it, you need to add this line to one of the cpp files, like this:
#include "myh.h"
int foo;
int main()
{
foo=7;
print_foo();
print(99);
return 0;
}
The problem is that foo is declared but not defined. You need to define foo in exactly one of the translation units, e.g.:
int foo = 0;

What is the relationship between multiple header files and classes?

I have a noob question here.
I'm getting my head around the C++ structure and syntax and I've hit a bit of a wall.
I know I am missing something from my concept. So first a little code to help describe the situation.
Control.h
#pragma once
#ifndef CONTROL_H
#define CONTROL_H
class Control
{
public:
Control();
~Control();
private:
public:
};
#endif /*CONTROL_H*/
Control.cpp
#include "Control.h"
#include "Hello.h"
Hello helloObj;
Control::Control()
{
}
Control::~Control()
{
}
int main()
{
int a = helloObj.HelloWorld();
return 0;
}
Hello.h
#pragma once
#ifndef HELLO_H
#define HELLO_H
class Hello
{
public:
Hello();
~Hello();
private:
public:
int HelloWorld(void);
};
#endif /*HELLO_H*/
Hello.cpp
#include "Hello.h"
Hello::Hello()
{
}
Hello::~Hello()
{
}
int HelloWorld()
{
return 5;
}
I try and compile control.cpp with g++ on OSX 10.7 and get
Undefined symbols for architecture x86_64:
"Hello::Hello()", referenced from:
__static_initialization_and_destruction_0(int, int)in cccZHWtd.o
"Hello::~Hello()", referenced from:
___tcf_1 in cccZHWtd.o
"Hello::HelloWorld()", referenced from:
_main in cccZHWtd.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Is it the compiler, my code or my concept of whats going on?
Am I not instantiating something correctly?
Any links describing this in more detail would be appreciated.
Ultimately I want to be able to run a function in another class and return the result...normal OO, keeping your program modular stuff....
The errors you are getting are Linking errors not compilation errors.
The linker is not able to find definitions of the said functions & hence it reports the errors. It seems You have not included the Hello.cpp file containing the function definitions in your project.
Make sure Hello.cpp is included in your project and is a part of your project or
If you are using command line for compilation and linking make sure you have specified Hello.cpp in the file names on the command line.
Most of the issue is me not being familiar as I should be with g++ (Thanks Als).
There were are few syntax issues as well (Thanks Brain).
Here is the corrected (albiet slightly bloated for an overview of stucture) code and g++ command
Control.h
#pragma once
#ifndef CONTROL_H
#define CONTROL_H
class CONTROL
{
private:
//nothing defined yet...
public:
Control(); //default constructor
~Control(); //default destructor
};
#endif /*CONTROL_H*/
Control.cpp
#include "Hello.h"
#include "Control.h"
Hello helloTest; //instantiates the Hello Object
Control::Control()
{
}
Control::~Control()
{
}
int main()
{
helloTest.HelloWorld();
return 0;
}
Hello.h
#pragma once
#ifndef HELLO_H
#define HELLO_H
class Hello
{
private:
//nothing defined yet
public:
Hello(); //default constructor
~Hello(); //default destructor
void HelloWorld();
};
#endif /*HELLO_H*/
Hello.cpp
#include "Hello.h"
#include <iostream> //so we can use 'cout'
using namespace std;
Hello::Hello()
{
}
Hello::~Hello()
{
}
void Hello::HelloWorld()
{
std::cout << "Hello lovelies!\n"; //The magic word.
}
Then we run g++ like so
g++ -o Hello ./Control.cpp ./Hello.cpp
g++ [option] [output file name] [input files]
First of all:
public:
Hello();
~Hello();
private:
public:
is pointless, a class defaults to private, and there is no need to make it
public twice nor do I know if you can do that furthermore if you have no private members private should not be in there (not trying to be mean just some advice :-) )
Now to answer the question (with a guess DISCLAIMER: I AM NOT 100% FAMILIAR WITH GCC):
This is a linker error, it may be there because
the compiler can not find the definition of
HelloWorld(void);.
Let me explain:
In your header file you wrote:
int HelloWorld(void);
However in your .cpp you write:
int HelloWorld()
{
return 5;
}
The function's (or in this case method because it is inside a class)
arguments need to be exactly the same in the header and source, you
can not even change the names (or at least you cant with VC++ which is
what I use; I have little experience with gcc) so this may be resolvable
by typing
int HelloWorld(void)
{
return 5;
}
Next (DISCLAIMER I AM NOT 100% familiar with the pre-proccsor):
You also use the #pragma once pre-proccsor tag, I dont use it but
I believe that means you can only include a file once and you have included Hello.h and Control.h twice, like I said I am no expert in the pre-proccsor but you commented out
HELLO_H
and
CONTROL_H

Nested class, undefined reference, static method

I have problem and no idea how to resolve it. I believe this is stupid trivial:
I have 3 files:
Util.hpp
class Util
{
public:
class BitParser
{
public:
static bool getBitAt(int buf, int idx);
};
};
Util.cpp
#include "Util.hpp"
bool Util::BitParser::getBitAt(int buf, int idx)
{
return true;
}
application.cpp
#include "Util.hpp"
int main(int argc, char* argv[])
{
Util::BitParser::getBitAt(1,1);
}
Of couse, files listed above are in the same directory. And now when I try to link and compile I recieve linker error:
$ g++ -o app application.cpp
application.cpp:(.text+0x19): undefined reference to `Util::BitParser::getBitAt(int, int)'
collect2: ld returned 1 exit status
What is screwed up?
You told g++ to compile your 'main' program, but didn't tell it about the Util module. Add Util.cpp to the command line and all should work well.
The compiler has brewn an "application.o" file that refers to the Util::bitparser functions.
The linker should 'link' these referrals to the "util.o" file, containing the actual code for these functions. But it has no .o file containing a function satisfying the link. That's what it calls "undefined reference": "application.o" refers to a function the linker doesn't find.
You need to compile (and link) all the .cpp files. So in your case, the command would be
$ g++ -o app application.cpp Util.cpp
Better still, write a Makefile to do this for you.
You have to include both application.cpp and Util.cpp in the build.