Compiling with Templates


The normal way to set up a program that uses a class is to have three files: the class header file with a .h extension, a class implementation file with a .cpp extension, and a program file also with a .cpp. The program file has a #include for the class header file, and the program and class are linked by compiling them together. The set up looks like this example:

FooClass.h       FooClass.cpp               Program.cpp
-----------      ---------------------      ---------------------
class Foo {      #include "FooClass.h"      #include "FooClass.h"
....             ....                       int main(void) {
....             ....                       Foo AFooInstance;
....             ....                       ....
};               ....                       }
-----------      ---------------------      ---------------------

prompt> g++ Program.cpp FooClass.cpp -o Program
Unfortunately, g++ does not cope easily with templates when a template class is declared in one file and an instance of the class is defined in another. The easiest way to overcome this is to include the class implementation file in the program file, and compile just the program file. The set up looks like this exmaple:
FooTClass.h             FooTClass.cpp               Program.cpp
------------------      ----------------------      ------------------------
template <class T>      #include "FooTClass.h"      #include "FooTClass.cpp"
class FooT {            ....                        int main(void) {
....                    ....                        FooT<int> AFooTInt;
....                    ....                        ....
};                      ....                        }
------------------      ----------------------      ------------------------

prompt> g++ Program.cpp -o Program