开发者

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开发者_StackOverflow 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.


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>;


Quoting from www.cplusplus.com

Because templates are compiled when required, this forces a restriction for multi-file
projects: the implementation (definition) of a template class or function must be in the same file as its declaration. That means that we cannot separate the interface in a separate header file, and that we must include both interface and implementation in any file that uses the templates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜