C++ error, Undefined reference class

允我心安 提交于 2021-02-05 09:25:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!