Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't link header files to my main.cpp in VScode (macOS) (clang error)

I am trying to link a header file which has a class defined in it and a .cpp file that has the actual functions of that class to my main cpp file but I'm getting this error:

c++ DataMembers.cpp -o DataMembers Undefined symbols for architecture x86_64: "Cat::eat()", referenced from: _main in DataMembers-053507.o "Cat::meow()", referenced from: _main in DataMembers-053507.o "Cat::sleep()", referenced from: _main in DataMembers-053507.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [DataMembers] Error 1

Please note that all files exists in the same directory!

my main.cpp code is:


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

using namespace std;

int main()
{
    Cat myCat;

    myCat.eat();
    myCat.meow();
    myCat.sleep();
}

my Cat.h code:

#ifndef CAT_H_
#define CAT_H_

class Cat 
{
public:
    void meow();
    void sleep();
    void eat();
};

#endif

and Cat.cpp code is:


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

void Cat::meow()
{
    cout << "Meowwwwww!" << endl;
    return;
}

void Cat::sleep()
{
    cout << "Zzz ... " << endl;
    return;
}

void Cat::eat()
{
    cout << "Num Nom Nom .. Yummy" << endl;
    return;
}

Interesting thing is when I change the header file in my main.cpp from #inclue "Cat.h" into #include "Cat.cpp" the program compiles without any issues! I just don't know why?

I have searched for a solution but couldn't find any yet! and I need to be able to use header files I create myself!

Thank you in advance friends!

like image 803
The_M_Code Avatar asked Nov 23 '25 07:11

The_M_Code


1 Answers

When compiling make sure that you reference all the cpp source files so it can generate the according object files.

It seems like you forgot to reference cat.cpp. The compiler sees that you have a header file included, assuming the implementation of this class will be in another cpp file. Because you forgot to reference the said file, the linker will complain that some undefined symbols cannot be linked.

Once you included the cat.cpp directly into your main.cpp, you basically copied all its contents to this file, which means there is no need anymore to link the implementation from another translation unit.

In short: you need to tell your compiler about cat.cpp

like image 133
Max Drießen Avatar answered Nov 24 '25 22:11

Max Drießen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!