-1

I faced a weird linking problem when trying to compile my source code. I paste my code below for better explanation.

LinkedList.h

#ifndef _LINKED_LIST
#define _LINKED_LIST

#include <iostream>
#include "ListInterface.h"
#include "Node.h"
#include "PrecondViolatedExcep.h"

template<class ItemType>
class LinkedList : public ListInterface<ItemType>{............
//There is the some code here, but thats not the point so i don't

#include "LinkedList.cpp"
#endif

main.cpp

#include "LinkedList.h"

int main()
{
    LinkedList<int> list;
}

You can see that under the LinkedList.h header file, i included this line #include "LinkedList.cpp at the bottom.

So now i can compile like this: g++ main.cpp -o main. This give me no problem at all the program works correctly.

But the linking problem appear when i remove this line #include "LinkedList.cpp at the bottom of LinkedList.h header file. And i compile like this: g++ main.cpp LinkedList.cpp -o main. Theoretically this should not be a problem, i done this most of the time with other projects. So this problem is kind weird for me. Can anyone pointing out what is the cause of this?

Makoto
  • 104,088
  • 27
  • 192
  • 230
Terry Tan
  • 421
  • 5
  • 12

2 Answers2

3

I assume the error happens because some methods for the template class are beind defined on the LinkedList.cpp file. Remember that C++ compiles individual code for each template specialization.

When main.cpp uses LinkedList<int>, some of its methods are not defined, so the linker will complain they are missing.

When making a template class, all the bodies for the methods should be in the header file too.

Please, read this, which seems to be your problem.

You could just add template class LinkedList<int>; on the bottom of your LinkedList.cpp file as well, this is called an explicit instantiation.

paulotorrens
  • 2,286
  • 20
  • 30
0

Chances are you are not including LinkedList.h in LinkedList.cpp so when it is compiled by itself (not in main.cpp) the compiler is making some assumptions about declarations of the constructs defined at the top of main.cpp and LinkedList.h. Resolve the includes for the separate LinkedList.cpp and that should fix the error.

Bruce
  • 2,230
  • 18
  • 34