mardi 3 août 2021

Why does this C++ program have problems linking with undefined reference error?

For some reason, I'm having a lot of trouble lately with creating classes with multiple files because an undefined reference error keeps showing up.

Here's the code:

Card.h

class Card {
    char name;
    
    public:
    char getName();
    void setName(char);
    Card();
    Card(char);
};

Card.cpp

#include "Card.h"

Card::Card()
{
    name = '-';
}

Card::Card(char _name)
{
    name = _name;
}

void Card::setName(char _name)
{
    name = _name;
}

char Card::getName() 
{
    return name;
}

main.cpp

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

int main()
{
    std::cout << "Welcome to deck of cards!" << std::endl;
    
    Card card;
    card.setName('A');

    std::cout << card.getName() << std::endl;
    return 0;
}

I get the program running by compiling and building:

g++ -c *.cpp
g++ -o Card.o main.o

This is the error:

/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x4b): undefined reference to `Card::Card()'
/usr/bin/ld: main.cpp:(.text+0x5c): undefined reference to `Card::setName(char)'
/usr/bin/ld: main.cpp:(.text+0x68): undefined reference to `Card::getName()'
collect2: error: ld returned 1 exit status

I know it has something to do with the linker not recognizing the methods. But the methods exist, right?

Aucun commentaire:

Enregistrer un commentaire