category : c,c++
keyword : dll export, stl

이 글은 How to export an instantiation of a Standard Template Library (STL) class and a class that contains a data member that is an STL object 를 정리한 것입니다. 자세한 내용은 원문을 참고하세요.

제약 사항
1. 우선 초기화 되지 않은 template는 export하지 못한다. 즉 export하고자 하는 template 클래스는 초기화 되어 있어야 한다.
template 의 경우 특정 type으로 구체화 되지 전에는 export되지 않는다. export하기 위해서는 구체화해야 하는데 vector를 예로 들면 vector 자체는 export할 수 없으나 int형으로 구체화된 vector<int>같은 경우는 export할 수 있다.
2. container 중에는 export할수 없는 것들(map, set, queue, list, deque)도 있다.
3. export하기 위해서는 nested 즉 내부에 포함되는 클래스 모두가 export되어야 한다.
그러한 이유로 map, set, queue 와 같은 container들은 내부에 포함된 클래스를 export할 수 없으므로 export할 수 없다. 현재 export가능한 container는 vector뿐이다.

결론
template class를 export하고 싶은 경우는 template이 구체화 될수 있도록 모든 관련 type들을 export해야 한다.

STL 클래스를 export하는 방법
export하고자 하는 구체화된 STL 클래스에 declspec specifier를 지정한다.
template class __declspec(dllexport) std::vector<int> vecInt ;

import하는쪽에서는 아래와 같이 선언해서 사용한다.
extern template class __declspec(dllimport) std::vector<int> vecInt ;

이렇게 선언하는 경우 compiler warning C4231 "nonstandard extension used : 'extern' before template explicit instantiation." 가 발생하는데 이것은 무시해도 된다.
#pragma warning (disable : 4231)

STL 클래스를 포함하는 class export하는 방법

stl class를 포함하는 MyClass를 export하는 경우를 생각해 보자.



MyClass를 export하기 위해서는 내부에 포함된 모든 template 관련 class들에 대한 구체화된 class를 export선언하고
EXPIMP_TEMPLATE template class DECLSPECIFIER std::vector<int>;
EXPIMP_TEMPLATE template class DECLSPECIFIER std::vector<char>;

그 다음 MyClass를 export한다.
EXPIMP_TEMPLATE template class DECLSPECIFIER std::vector<MyClass>;

MyClass의 operator <, == 는 STL container 에 포함되는 type인 경우 이 2가지 operator를 구현해야 한다.

당연히 export하는 쪽에서는 EXP_STL를 선언해야 하고 사용하는 쪽에서는 선언하지 않는다.
EOF

+ Recent posts