简体   繁体   中英

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.

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.

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"

使用代码块13.12我右键单击Burritto.cpp文件,选择“属性”,然后选择“构建”选项卡,并选中“编译文件”和“链接文件”复选框,然后单击“确定”,保存所有内容,然后运行,效果很好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM