Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit instantiation of function template fails (g++)

I am experiencing some problems (i.e, linkage errors) with explicit instantiation of a function template. Under Visual Studio the project links ok, only under g++/Unix, using Eclipse-CDT, the linkage produce errors.

The function call is a part of a static library, which is linked with a dynamic library, in a big project. The architecture of the function is as follows:

  • function template declared (but not implemented) inside a namespace in my MathUtils.h file. One of the function arguments is itself a struct template, which is declared and implemented in this h file (under the same namespace).
  • function implementation and instantiation is in MathUtils.cpp.
  • function call is in someFile.cpp (which of course #include "MathUtils.h") which is compiled & linked as a part of a static library.

The thing that drives me (almost) crazy, is that the build errors are not fully reproducible, and I suspect the Eclipse is to be blamed (maybe skipping some steps, although I use clean project before each build).

For about an hour, the Debug configuration built w/o errors but the Release failed with undefined reference to... linkage error. Then, for the next hour, both configurations failed. Then I made a small project, with only the 3 files mentioned above, and compiled it both from the command line and from Eclipse - no errors at all. Now Both configurations seem to link ok.

Did anyone experienced similar issues using the Eclipse-CDT? Any suggestions?

EDIT: since the problem is not easily (or at all) reproducible, I guess it will be hard to get an answer. I will update if I have any new insights.

like image 422
Itamar Katz Avatar asked Dec 06 '10 17:12

Itamar Katz


1 Answers

I had a similar problem. Solved it by moving instantiation after implementation in the .cpp with the class implementation.

myclass.hpp:

template <class T>
class MyClass
{
public:
    MyClass();
    // other declarations
};

myclass.cpp:

#include "myclass.hpp"

template <class T>
MyClass<T>::MyClass()
{
}

template class MyClass<int>;
template class MyClass<bool>;
like image 147
Melebius Avatar answered Sep 23 '22 13:09

Melebius