I have to deal with a library that consists of many templated classes, which are of course all implemented in header files. Now I'm trying to find a way to reduce the unbearably long compile times that come from the fact that I pretty much have to include the whole library in each and one of my compilation units.
Is using forward declarations a possibility, despite the templates? I'm trying something along the lines of the example below, where I attempted to get around the #include <vector>
, as an example, but it's giving me a linker error because push_back
is undefined.
#include <iostream>
namespace std {
template<class T>
class vector {
public:
void push_back(const T& t);
};
}
int main(int argc, char** argv) {
std::vector<int>* vec = new std::vector<int>();
vec->push_back(3);
delete vec;
return EXIT_SUCCESS;
}
$ g++ fwddecl.cpp
ccuqbCmp.o(.text+0x140): In function `main':
: undefined reference to `std::vector<int>::push_back(int const&)'
collect2: ld returned 1 exit status
I tried precompiled headers once but that didn't change the compile times at all (I did make sure they were indeed loaded instead of the real headers). But if you all say that precompiled headers should be the way to go then I'll give that a try again.
UPDATE: Some people say it's not worth to forward-declare the STL classes. I should stress that the STL vector
above was just an example. I'm not really trying to forward-declare STL classes, but it's about other, heavily templated classes of some library that I have to use.
UPDATE 2: Is there a way to make above example actually compile and link properly? Logan suggests to use -fno-implicit-templates
and put template class std::vector<int>
somewhere, presumably into a separate .cpp
file that gets compiled with -fno-implicit-templates
, but I still get linker errors. Again, I'm trying to understand how it works for std::vector
so that I can then apply it to the templated classes that I'm actually using.