【发布时间】:2010-12-20 23:13:19
【问题描述】:
我有一个配置项目:
./main.cpp
./type_traints/TypeTraints.cpp
./type_traints/TypeTraints.hpp
./type_traints/chapter_20.hpp
./type_traints/CMakeLists.txt 文件是:
cmake_minimum_required (VERSION 2.8)
add_library(chapter_20 TypeTraints.cpp)
./CMakeLists.txt 如下:
cmake_minimum_required (VERSION 2.8)
project (mpl)
add_subdirectory(type_traints)
include_directories(type_traints)
link_directories(type_traints)
add_executable (mpl main.cpp)
target_link_libraries(mpl chapter_20)
文件的相关部分(大部分包括省略)包括:
./type_traints/chapter_20.hpp
#ifndef CHAPTER_20_GUARD
#define CHAPTER_20_GUARD
#include <TypeTraints.hpp>
void chapter_20() {
test_23();
}
#endif //CHAPTER_20_GUARD
./type_traints/TypeTraints.hpp
#ifndef TYPE_TRAINTS_GUARD
#define TYPE_TRAINTS_GUARD
namespace details {
template<class T> const char* class2name() {
return "unknown";
};
template<> const char* class2name<int>() {
return "int";
};
}
template<class T>
class type_descriptor {
friend std::ostream& operator << (std::ostream& stream,
const type_descriptor<T>& desc) {
stream << desc.getName();
return stream;
}
public:
std::string getName() const;
};
template<class T>
std::string type_descriptor<T>::getName() const {
return details::class2name<T>();
}
void test_23();
#endif // TYPE_TRAINTS_GUARD
./type_traints/TypeTraints.cpp
#include<TypeTraints.hpp>
void test_23() {
cout << type_descriptor<int>() << endl;
}
和./main.cpp
#include <chapter_20.hpp>
int main(int argc, char* argv[]) {
chapter_20();
return 0;
}
项目编译但链接失败:
[ 50%] Building CXX object type_traints/CMakeFiles/chapter_20.dir/TypeTraints.cpp.o
Linking CXX static library libchapter_20.a
[ 50%] Built target chapter_20
[100%] Building CXX object CMakeFiles/mpl.dir/main.cpp.o
Linking CXX executable mpl
type_traints/libchapter_20.a(TypeTraints.cpp.o): In function `char const* details::cl
ass2name<int>()':
/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:312: multiple definition of `c
har const* details::class2name<int>()'
CMakeFiles/mpl.dir/main.cpp.o:/home/marcin/Projects/mpl/type_traints/TypeTraints.hpp:
312: first defined here
collect2: ld returned 1 exit status
make[2]: *** [mpl] Błąd 1
make[1]: *** [CMakeFiles/mpl.dir/all] Error 2
make: *** [all] Error 2
23:56:20@marcin-laptop ~/P
如果我从 TypeTraints.hpp 中删除 class2name 特化 (class2name<int>()) 并仅使用通用实现,则项目链接正常。
有人知道为什么会这样吗?我是否错过了配置 cmake 文件?
【问题讨论】:
标签: c++ templates definition