给出以下示例,使用GNU / Linux下的GCC:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(export_templates CXX)
include(GenerateExportHeader)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
add_library(mylib SHARED header.hpp mylib.cpp)
generate_export_header(mylib)
add_executable(myexe header.hpp main.cpp)
target_link_libraries(myexe mylib)
header.hpp:
#pragma once
#include <vector>
template<typename T>
struct foo
{
std::size_t bar() {
std::vector<T> t;
t.resize(10);
return t.size();
}
};
extern template struct foo<int>;
mylib.cpp:
#include "header.hpp"
#include <mylib_export.h>
template struct MYLIB_EXPORT foo<int>;
main.cpp中:
#include "header.hpp"
int main()
{
foo<int> f;
return f.bar();
}
我收到以下链接器错误:
[ 75%] Linking CXX executable myexe
CMakeFiles/myexe.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `foo<int>::bar()'
我可以做些什么来实现此链接,具有以下要求:
MYLIB_EXPORT
添加到struct foo
的定义中(因为在实际情况下,struct foo
不在我的控制之下)。