Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VSCode compile C++ with external classes – undefined reference to `MyClass::MyClass()'

Error when compiling my main file & external Class file using VScode.

file structure:

project/
 --main.cpp
 --MyClass.cpp
 --MyClass.h

MyClass.h

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#ifndef MY_CLASS_H
#define MY_CLASS_H

class MyClass
{
public:
    MyClass();
};

#endif

MyClass.cpp

#include "MyClass.h"
#include <iostream>
#include <string>

MyClass::MyClass()
{
    std::cout << "MyCLass is created" << std::endl;
}

main.cpp

#include <iostream>
#include <string>
#include "MyClass.h"

int main()
{
    MyClass myClass;
    return 0;
}

Compile error:

main.cpp:9: undefined reference to `MyClass::MyClass()’

>Solution :

Change main.cpp’s includes to:

#include <iostream>
#include <string>
#include "MyClass.cpp"

By including MyClass.cpp in main.cpp and compiling like this:

g++ -o main main.cpp

you end up including MyClass.h by virtue of it being included in MyClass.cpp. By including MyClass.cpp, you can successfully compile.

If you want to keep your code as it currently is, you can instead change your compilation to be:

g++ -o main main.cpp MyClass.cpp

Which will include MyClass.cpp in compilation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading