问题
Why does codeblocks give this error "Undefined reference to class::classfunction()" It happens when a class is created in a separated file.All of these files are in the same folder
This is the main .cpp file
#include<iostream>
#include "Class2.h"
using namespace std;
main()
{
Class2 classObject;
cout<<"I'm class2"<<endl;
}
class header file
#ifndef CLASS2_H
#define CLASS2_H
class Class2
{
public:
Class2();
~Class2();
protected:
private:
};
#endif // CLASS2_H
class cpp file
#include "Class2.h"
#include<iostream>
using namespace std;
Class2::Class2()
{
cout<<"Hello, I'm Constructor"<<endl;
}
Class2::~Class2()
{
cout<<"Yo!! I'm Destructor"<<endl;
}
error is "undefined reference to Class2::Class2()"
回答1:
You need to link both main.o
and class.o
into your executable. The exact command depends on your compiler and OS. For g++ the command would look something like
g++ -o main main.cpp class.cpp
来源:https://stackoverflow.com/questions/21643394/c-error-undefined-reference-class