2

I have defined a class Cat which has a member function void Cat::miao() in Cat.h file. Then , I implement this function in Cat.cpp as the following code.

However, while compiling and linking, I got an error , say , "undefined reference to `Cat::miao()" .What wrong with the code?

My compiler is GNU c11.

-----Cat.h

#include<iostream>
#include<string>
using namespace std;
class Cat
{
    string name;
    public:
        Cat(const string&n):name(n){};
        void miao();
};

-----Cat.cpp

#include"Cat.h"
void Cat::miao()
{
    cout << name << endl;
}

-----main.cpp

#include"Cat.h"
int main()
{
    Cat tom("tom");
    tom.miao();
    return 1;
}

Compiling with:

g++ main.cpp

results in this error:

C:\Users****:K.o:main.cpp:(.text+0x69): undefined reference to `Cat:: miao()' collect2.exe: error: ld returned 1 exit status

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
W.Cameron
  • 124
  • 10

2 Answers2

2

Cat.cpp is not being properly linked to main.cpp in the final linking part of the compilation process.

Compiling using the command g++ main.cpp will attempt to compile and link main.cpp. Cat.cpp is not being compiled and linked to main.cpp because you did not specify its name on the command line.

Probable fix : Use g++ main.cpp Cat.cpp when compiling.

It is also recommended that you setup a Makefile or another build manager if you plan on making a big project, though if you're just doing this for a tutorial and are going to throw this code away in 5 minutes, this is not really needed.

Gabriel Ravier
  • 358
  • 1
  • 6
  • 17
0

Try this

-----Cat.h

#include<iostream>
#include<string>
using namespace std;
class Cat
{
    string name;
    public:
        Cat(const string&n):name(n){};
        void miao();
};

-----Cat.cpp

#include"Cat.h"
void Cat::miao()
{
    cout << name << endl;
}

-----main.cpp

#include"Cat.h"
int main()
{
    Cat tom("tom");
    tom.miao();
    return 1;
}

Compiling with:

g++ main.cpp  cat.cpp

And surely it will work.

Hamza.S
  • 1,319
  • 9
  • 18