samedi 30 janvier 2021

An issue with #include statements [duplicate]

I am very new to C++ so please bear with me. I have the following five files:

// main.cpp
#include <iostream>
#include "food.h"
#include "food.cpp"
#include "dog.h"

int main(void)
{
    Food<int> *food = new Food<int>(10);
    Dog *dog = new Dog();
    dog->eat(*food);
    
    delete food;
    delete dog;
    
    return 0;
}
// food.h
#pragma once

template <class T>
class Food
{
public:
    Food(T value);
    ~Food();
    
    T value;
};
// food.cpp
#include "food.h"

template <class T>
Food<T>::Food(T value): value(value) {}

template <class T>
Food<T>::~Food() {}
// dog.h
#pragma once

class Dog
{
public:
    Dog();
    
    ~Dog();
    
    template <class T>
    void eat(Food<T>& food);
};
// dog.cpp
#include <iostream>
#include "food.h"
#include "dog.h"

Dog::Dog() {}

Dog::~Dog() {}

template <class T>
void Dog::eat(Food<T>& food)
{
    std::cout << "Eating food\n";
}

And when I compile with the command

g++ main.cpp food.cpp dog.cpp -o main

I get the error

Undefined symbols for architecture x86_64:
  "void Dog::eat<int>(Food<int>&)", referenced from:
      _main in main-083267.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I think the issue is related to the #include statements in my main.cpp but I've been racking my brain for over an hour trying different things and can't for the life of me figure it out.

Aucun commentaire:

Enregistrer un commentaire