David G
David G

Reputation: 96810

Beginner working with objects and classes getting the following errors

This is a tutorial I've been following and I've done everything that it tells but it doesn't work. I have three files: the main.cpp, burrito.h (the class), and burrito.cpp.

And here are the three files respectively.

main.cpp

#include <iostream>
#include "Burrito.h"
using namespace std;

int main() {

    Burrito bo;

    return 0;
}

Burrito.h

#ifndef BURRITO_H
#define BURRITO_H


class Burrito {
    public:
        Burrito();
};

#endif // BURRITO_H

Burrito.cpp

#include <iostream>
#include "Burrito.h"

using namespace std;

Burrito::Burrito() {
    cout << "Hello World" << endl;
}

When I build and run I get the following error:

...undefined reference to `Burrito::Burrito()'
collect2: ld returned 1 exit status
Process terminated with status 1 (0 minutes, 6 seconds)
1 errors, 0 warnings

I'm compiling using CodeBlocks.

Upvotes: 0

Views: 324

Answers (3)

Hillid
Hillid

Reputation: 1

Using Code Blocks 13.12 I right clicked on the Burritto.cpp file chose Properties, then chose the Build tab and checked the compile file and link file check boxes then clicked ok saved everything then ran and it worked great.

Upvotes: 0

Salepate
Salepate

Reputation: 327

When you're linking objects together to get the final executable file you're forgetting to link the compiled-object from burrito.cpp file correctly

If you're building with a Makefile, your final output rule should have something like "-o main main.o burrito.o"

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545618

I'm using CodeBlocks

This is the issue.

If you’re starting to learn C++ it’s (unfortunately) essential to learn about translation units. An IDE like Code::Blocks hides this detail from you – and does it wrong, in this case (this isn’t really the fault of Code::Blocks though, it can’t automatically guess what to do in this case without configuation).

In the beginning, drop the IDE, go to the command line for compiling. Compile the two translation units separately and link them together explicitly.

g++ -o burrito.o burrito.cpp
g++ -o main.o main.cpp
g++ -o main main.o burrito.o

Every good beginners’ C++ book will explain how this works.

Upvotes: 5

Related Questions