Problem with template Class and file linking

I have a cpp program consisting of a three files:

1. parser.h: includes the definition of a "template" class :

template <class PType> class parser {
....
}

no function is defined inside the class, only the prototypes.

2. parser.cpp: includes the definition of member function:

#include "parser.h"
...
member function definitions


3. RunParser.cpp: a test run on the template class:

the probelm is that inside the RunParcer.cpp,complier finds the following line an error:

parser < double > ob;

reporting: (I am using Eclipse)

"undefined reference to `parser<double>::parser()"


the point is that if I put all the definitions of parser.cpp inside parser.h everything runs smoothly.
or if I put all the code of RunParser.cpp inside parcer.cpp, again there will be no error.
also if I remove the template format and define everything as of type for example double, again everything runs smoothly with no error.

I guess there is a problem with linking of the 3 files, or maybe namespace.

Can anyone help me on this? why do I get an error if I have a template class defined in one file, all its member functions defined in another file and a third file defines specific instances of the template class?
You can't move the definitions of templates in a separate source file, you need to keep everything in the header

- Standard C++ has the keyword export for this but most compilers don't implement it -
Many thanks for your help Bazzy

I have a very related question:
I have a header file test.h and a cpp file test.cpp which defines the functions inside test.h
(no template or whatsoever, everything simple)

and I have put both file in the headers file directory (say /usr/include under linux)

again I run into the same problem if I want to use test.h in another program,
that is although I add

#include <test.h>

my program finds "test.h" but cannot see "test.cpp" and I have to include all test.cpp code inside test.h for my program to be run. there is no template in this case, I have just moved test.h and test.cpp from working directory to "/usr/include"


Can you help me with this issue? Many thanks in advance.
You need to link to your file.
You can compile your test.cpp to a library - eg: test.a - ( then you should put it into /usr/lib )
Then pass your library to the linker (thats depends on which IDE/compiler you are using)

You can still keep test.cpp as source file but you'll need to re-compile it each time

Any solution you choose, the point is that your compiler must know which file to compile/link
Topic archived. No new replies allowed.