编译器错误地包含同一目录中的文件

Thi*_*201 2 c++ gcc compiler-errors

第一次使用堆栈溢出。我正在尝试实践面向对象的抽象和接口。我一直无法编译程序,我的程序如下。

主程序

#include "Spells.h"

#include <iostream>

int main()
{
    spell MagicalSpell;
    std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)

Spells.h

#pragma once

class spell {
private:
    int EnergyCost;
public:
    spell();
    ~spell();
    void SpellEffect();

};
Run Code Online (Sandbox Code Playgroud)

拼写.cpp

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

spell::spell() {
    EnergyCost = 0;
}

spell::~spell() {

}

void spell::SpellEffect(){
    std::cout << "woosh" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

每次我尝试编译 main.cpp 时,我都会得到:

g++     main.cpp  -lcrypt -lcs50 -lm -o main
/tmp/ccnXk1TN.o: In function `main': 
main.cpp:(.text+0x20): undefined reference to `spell::spell()'
main.cpp:(.text+0x3f): undefined reference to `spell::~spell()'
main.cpp:(.text+0x64): undefined reference to `spell::~spell()'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'main' failed
make: *** [main] Error 1
Run Code Online (Sandbox Code Playgroud)

以下链接似乎描述了大部分问题。 https://askubuntu.com/questions/902857/error-tmp-ccob6cit-o-in-function-main-example-c-text0x4a 那个人似乎在使用标准库,我想我只是在尝试使用个人同一目录下的文件。

我以前在课堂作业中一起使用过多个文件,但没有遇到过这个问题。我仍然可以编译和执行这些文件。我在让文件相互包含时犯了一个错误吗?我应该使用不同形式的 gcc 编译命令吗?

Bri*_*ian 7

你没有传递Spell.cpp到g++.

使用您提供的选项,g++将尝试编译其参数中列出的文件并将生成的目标文件链接在一起以生成最终的可执行文件。但是,由于Spell.cpp从未编译过,因此链接器无法找到spell::spellor 的定义spell::~spell。

最简单的解决方法是将所有翻译单元提供给g++,例如

g++ main.cpp Spell.cpp -o main 
Run Code Online (Sandbox Code Playgroud)