Alexander Kleinhans
Alexander Kleinhans

Reputation: 6258

"Undefined symbols for architecture x86_64" in terminal but no error in xcode

This is driving me nuts. I don't understand what the error is telling me and it only appears when I compile using the terminal and call the function. If I include the class.h, make a member called "first", there is no error, but if I call the function "first.coutTest()" there is an error, BUT NO ERROR WHEN I USE XCODE!

Why am I getting an error in terminal?!

this is main.cpp

#include <iostream>
#include <string>
#include "class.h"
using namespace std;

int main(void){
    TestClass first;    
    first.coutTest();   
    cout << "test" << endl; 
    return 0;
}

here is my class.h

#include <iostream>
#include <string>
using namespace std;

class TestClass{
    int number;
public:
    void coutTest();
};

here is my class.cpp

#include <iostream>
#include "class.h"
using namespace std; 

void TestClass::coutTest(){
    cout << "class test" << endl;
}

Again, no error when I run it in xcode, so xcode must be doing something I'm not. Could someone please tell me what's going on?

Specific error I get is when I use make or g++ is the same:

Undefined symbols for architecture x86_64:
  "TestClass::coutTest()", referenced from:
      _main in main-f2c376.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 am running Yosemite 10.10.1 on a MacBook Pro (15-inch, Late 2011) Processor 2.2 GHz Intel Core i7 with Graphics Intel HD Graphics 3000 384 MB.


Edit update:

So now I've got it working in terminal when I include "class.cpp" instead of "class.h". I was my understanding that this is bad practice, so I'm hesitant to do this. Why does xcode have me include files differently. Why doesn't program work the same way in terminal?

Upvotes: 2

Views: 3260

Answers (1)

Shanti K
Shanti K

Reputation: 2918

You will need to compile all the cpp files. Hence do this:

g++ main.cpp class.cpp

Or, to individually compile and link the cpp's.. , use -c option Do this:

g++ -c main.cpp
g++ -c class.cpp
g++ main.o class.o

Or, if all you cpp files are under the same directory, navigate to that directory and do this:

g++ *.cpp

Upvotes: 3

Related Questions