I have a C++ class library project that is commonly used by other C++ projects. To be able to use classes inside my class library project, I wrote a header file like the example given below
#pragma once
#ifdef MYLIB
# define MYLIB_EXPORT __declspec(dllexport)
#else
# define MYLIB_EXPORT __declspec(dllimport)
#endif
No problem until I want to create a template class inside my class library project. The problem is I can’t export my template class.
MyClass.h
template<class T>
class MYLIB_EXPORT MyClass
{
void myMethod();
// ...
}
template<class T>
void MyClass::myMethod()
{
// ...
}
In this case I am getting compilaton errors saying “definition of dllimport function not allowed”. I know what causes the problem and I understand it. Other projects using my class library project converts the MYLIB_EXPORT keyword to __declspec(dllimport). Therefore, they are expecting the methods of MyClass to be defined in a DLL. But, then the compiler sees the definition inside the header.
How can I overcome this situation and be able to export my template classes that are defined inside my class library project?
Uninstantiated templates can’t be compiled directly – they are code generators, so they are actually translated to binary instructions only when they are instantiated; for this reason, you can’t export a template “in binary form” as if it was a “regular” function/class (on the other hand, at least in theory you could export an instantiation of a template).
Long story short: just leave the templates in a header to be included by library clients.
Notice that this is the exact reason why you keep templates in headers and you don’t normally separate their implementation in
.cppfiles.