Sunday 23 October 2016

c++ - Include .cpp file?











I've been trying around with C++ recently.
At the moment I'm trying to program something I'm sure everone has done at least once: A simple LinkedList class.
The code is done, but I'm somehow failing to compile it. I've been googling and it seems like I'm linking the object files wrong. That's what my code basically looks like:



test.cpp



#include "linkedlist.h"


int main()
{
LinkedList list;
// do something
}


linkedlist.h




template 
class LinkedList
{
// a lot of function and variable definitions
}


Then there's a .cpp file called linkedlist.cpp which contains all the actual code of the LinkerList class. When trying to compile test.cpp using the following command:



g++ ..\src\test.cpp



I'm getting told that there's an undefined reference to 'LinkedList::LinkedList()'. So I've been thinking that it's being linked wrong as there's more than one .cpp file, so I tried it like this:



g++ -c -Wall -O2 ..\src\test.cpp
g++ -c -Wall -O2 ..\src\linkedlist.cpp
g++ -s test.o linkedlist.o


However, this doesn't change anything. The error messages stay the same.

I've been trying to find some information on the internet, however, it didn't really work out.


Answer



You're creating a class template, which has the important caveat that all variable definitions must be placed in the header file so that they're accessible to all translation units during compilation.



The reason is the way that templates work. During compilation, the compiler instantiates template classes based on your class template definition. It isn't enough for it to have access to only the declarations or signatures: it needs to have the entire definition available.



Move all of your method definitions out of the .cpp file and into the .h file, and everything should be fine (assuming that you have, in fact, provided a definition for the default constructor!).



Alternatively, you might be able to get around this by explicitly telling your compiler to instantiate the appropriate template class using something like template class LinkedList, but this really isn't necessary in such a simple case. The primary advantage of this over including all of the definitions in the header file is that it potentially reduces code bloat and speeds up compilation. But it might not be necessary at all, as compilers have gotten a lot smarter at applying appropriate optimizations.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...