Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class method not found when compiled

Tags:

c++

g++

I created a simple class 'Hello' in C++ using header(.h) and definition(.cpp) files. This is the header file content:

#ifndef HELLO_H
#define HELLO_H

#include <string>

namespace test
{
    class Hello
    {
    private:
        std::string name;

    public:
        Hello();
        void say_hello();
    };
}

#endif

And the definition file content is just as you expected:

#include "Hello.h"
#include <iostream.h>

using namespace test;

Hello::Hello()
{
    this->name = "Yoppy Yunhasnawa";
}

void Hello::say_hello()
{
    string message = "Hello, " + this->name + ".. Have nice day!";

    cout << message << "\n";
}

I included this class to a main.cpp file and use it like this:

#include "Hello.h"

using namespace test;

int main(int argc, char *argv[])
{   
    Hello* hello = new Hello;

    hello->say_hello();
}

When I compiled the main.cpp file with g++ like this,

g++ main.cpp

I got following annoying error:

Undefined symbols for architecture x86_64:
  "test::Hello::say_hello()", referenced from:
      _main in ccsaoOZa.o
  "test::Hello::Hello()", referenced from:
      _main in ccsaoOZa.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

However, that error does not appear when I don't call both constructor and say_hello method:

int main(int argc, char *argv[])
{   
    Hello* hello;// = new Hello;

    //hello->say_hello();
}

I use macport GCC 4.7 and I am very sure that my method is there but why this symbol(s) not found error keep appearing? Please show me my mistake. Thank you.

like image 690
yunhasnawa Avatar asked Jan 13 '23 03:01

yunhasnawa


1 Answers

When you invoke g++ main.cpp, compiler performs both compiling AND linking. But the code cannot be linked without Hello.cpp file. So, you have two options: either compile and link separately:

g++ -c main.cpp
g++ -c hello.cpp
gcc main.o hello.o

or compile and link everything at the same time:

g++ main.cpp hello.cpp
like image 188
nullptr Avatar answered Jan 16 '23 19:01

nullptr