0

How can I use and consume a template class when it is compiled in a shared library and a static library?

For example, I have a library project:

/// Lib/Config.hpp
// if building a shared library
#ifdef LIB_BUILD_DLL
#  define LIB_API          __declspec(dllexport)
#  define LIB_TEMPLATE_API __declspec(dllexport)
#  define LIB_EXTERN
// exe projects use the shared library
#elif defined(LIB_DLL)
#  define LIB_API          __declspec(dllimport)
#  define LIB_TEMPLATE_API
#  define LIB_EXTERN       extern
// if building a static library, and exe projects use the static library
#else
#  define LIB_API
#  define LIB_TEMPLATE_API
#  define LIB_EXTERN
#endif
/// End of Lib/Config.hpp

/// Lib/Location.hpp
template<typename T>
LIB_EXTERN class Vector2;

class LIB_API Location
{
public:
     Vector2<float> point;
};
/// End of Lib/Location.hpp

/// Lib/Vector2.hpp
template<typename T>
LIB_EXTERN class LIB_TEMPLATE_API Vector2
{
public:
    template <typename U>
    explicit Vector2(const Vector2<U>& vector)
    {
        x = vector.x;
        y = vector.y;
    }

    Vector2<T> operator -(const Vector2<T>& right)
    {
        return Vector2<T>(x - right.x, y - right.y);
    }

    T x;
    T y;
};
typedef Vector2<float> Vector2f;
/// End of Lib/Vector2.hpp

And a exe main project:

#include "Lib/Config.hpp"
#include "Lib/Location.hpp"
#include "Lib/Vector2.hpp"

class Application
{
public:
    Location location_;
    Vector2<float> point_;
    Vector2f float_point_;
}

What I'd like to ask is if I correctly use LIB_EXTERN the right way?

And how can I pass a Vector2f object to a copy constructor Vector2(const Vector2<U>& vector)?

MiP
  • 5,846
  • 3
  • 26
  • 41
  • Closely related to [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Bo Persson Feb 03 '18 at 12:20

1 Answers1

0

You wouldn't normally export template functions or classes. They are compiled for each translation unit and cleaned up by linker as necessary. Simply including the .hpp file is all you need to compile the necessary code where it's needed.

KSquared
  • 58
  • 7