Question

Yes, I know this has been asked a billion times before, I've checked at least 100 duplicates of this question, and still haven't found an answer.

I'm getting undefined reference errors to all of my LList functions, although it all seems to be properly defined and linked. Since my code is a bit too long to paste here, I made a pastie: Click

I compile my code with: g++ driver.cpp box.cpp LList.cpp Song.cpp Album.cpp -o driver

Was it helpful?

Solution 2

Template classes and functions must be defined inline. Thats the problem. For example:

//box.h
#ifndef BOX_H
#define BOX_H

template <typename DataType>
struct box
{
        DataType data;
        box<DataType> *next;
        box(DataType d, box<DataType>* n)
        {
                data = d;
                next = n;
        }
};

#endif

And remove the .cpp file; you should do the same to the LList.h/cpp

OTHER TIPS

A class or function template is not a class or function and hence cannot be placed in a .cpp file like classes or functions. Rather, a template is a blueprint for how to make a class or function, namely a particular instantination of the template.

You can solve your problem in two ways:

1 either put all the templated code in the respective header files.

2 or instantinate the code explicitly in the .cpp files. For example

// Llist.cpp
#include Llist.hpp
#include Sonc.hpp

/* definition of members of Llist<> */

template class Llist<Song>;   // creates class Llist<Song> 

Solution 1 always works, but has the potential for HUGE header files and exposes all (or most) implementation details to the user. Solution 2 avoids huge headers and hides implementation details, but requires that you know which instantination you actually need (often impossible, in particular for such general concepts as linked lists).

Finally, solution 3: use the C++ standard library (std::list, std::forward_list) and don't worry.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top