2

First time using stack overflow. I am attempting to practice Object oriented abstraction and interfaces. I have been unable to get the program to compile, my program is as below.

main.cpp

#include "Spells.h"

#include <iostream>

int main()
{
    spell MagicalSpell;
    std::cout << "Hello World!\n";
}

Spells.h

#pragma once

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

};

Spell.cpp

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

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

spell::~spell() {

}

void spell::SpellEffect(){
    std::cout << "woosh" << std::endl;
}

Every time I attempt to compile main.cpp I get:

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

The following link seems to describe most of the issue. https://askubuntu.com/questions/902857/error-tmp-ccob6cit-o-in-function-main-example-c-text0x4a That person appears to be using a standard library, I think I am just attempting to use individual files that are in the same directory.

I have used multiple files together before from classwork and have not run into this problem. I can still get those files to compile and execute. Did I make a mistake in having the files include each other? Am I supposed to use a different form of a gcc compile command?

Valerii Boldakov
  • 1,751
  • 9
  • 19
Thing201
  • 23
  • 3
  • Those are linker errors, you are compiling main.cpp without errors. What you are missing is also compiling and linking in Spell.cpp. – Avi Berger Mar 12 '20 at 00:47
  • The title seems to have nothing to do with the question – M.M Mar 12 '20 at 01:00

1 Answers1

7

You aren't passing Spell.cpp to g++.

With the options you have provided, g++ will attempt to both compile the files listed in its arguments and to link the resulting object files together to produce a final executable. However, since Spell.cpp is never compiled, the linker cannot find a a definition for spell::spell or spell::~spell.

The simplest fix is to provide all translation units to g++, e.g.

g++ main.cpp Spell.cpp -o main 
Brian61354270
  • 8,690
  • 4
  • 21
  • 43