Error when compiling my main file & external Class file using VScode.
file structure:
project/
--main.cpp
--MyClass.cpp
--MyClass.h
MyClass.h
#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.