0

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()"

7
  • You never defined "class::classfunction()" Commented Feb 8, 2014 at 7:45
  • sorry, the error is "undefined reference to Class2::Class2()" Commented Feb 8, 2014 at 7:47
  • maybe try to switch the positions of include statements in the class cpp file? Commented Feb 8, 2014 at 7:48
  • tried switching their order. still gives same error Commented Feb 8, 2014 at 7:50
  • 3
    The is a linker error. In other words, the linker doesn't know it's also supposed to look in class.cpp. If you're using an IDE then it might not be part of the target. If you're using the command line then compile with g++ main.cpp class.cpp Commented Feb 8, 2014 at 7:50

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

sorry but where to enter this kind of code? I'm compiling directly through codeblocks. not via a terminal
@user3286581: I am no expert on CodeBlocks, but you probably need to create a project containing the two source files: wiki.codeblocks.org/index.php?title=Creating_a_new_project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.