cmake - 链接共享库失败

时间:2014-11-30 08:38:42

标签: c++ cmake dynamic-linking

我的项目结构如下。

.
├ main.cpp
├── include
│   └── stack.h
└── src
    └── stack.cpp

Main.cpp的:

#include <iostream>
#include "include/stack.h"

using namespace std;
int main() {

    Stack<int> intStack = Stack<int>();  // stack of ints
    Stack<string> stringStack = Stack<string>();    // stack of strings

    ...
}

stack.h

#include ...

template <class T>
class Stack {
...
}; 

stack.cpp

#include "../include/stack.h"

template <class T>
void Stack<T>::push (T const& elem) {
...
}

我的cmake文件如下

cmake_minimum_required(VERSION 2.8.4)
project(libbunch)

include_directories(${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(LIBRARY_NAME bunch)

file(
    GLOB_RECURSE
    SRC_FILES
    src/*
)

add_library(
    ${LIBRARY_NAME}
    SHARED
    ${SRC_FILES})

set(SOURCE_FILES main.cpp)
set(EXECUTABLE_NAME libbunch)
add_executable(${EXECUTABLE_NAME} ${SOURCE_FILES})

target_link_libraries (
    ${EXECUTABLE_NAME}
    ${LIBRARY_NAME}
)

它更像是一个通用的cmake而不是完全使用这些名称。这个cmake文件的问题是,当我运行它时,会发生以下错误。

[ 50%] Built target bunch
Linking CXX executable libbunch
CMakeFiles/libbunch.dir/main.cpp.o: In function `main':
main.cpp:13: undefined reference to `Stack<int>::push(int const&)'
main.cpp:14: undefined reference to `Stack<int>::top() const'
main.cpp:17: undefined reference to `Stack<std::string>::push(std::string const&)'
main.cpp:18: undefined reference to `Stack<std::string>::top() const'
main.cpp:19: undefined reference to `Stack<std::string>::pop()'
main.cpp:20: undefined reference to `Stack<std::string>::pop()'
collect2: error: ld returned 1 exit status
make[3]: *** [libbunch] Error 1
make[2]: *** [CMakeFiles/libbunch.dir/all] Error 2
make[1]: *** [CMakeFiles/libbunch.dir/rule] Error 2
make: *** [libbunch] Error 2

这显然意味着链接中存在错误,但我实际上是使用target_link_libraries链接cmakeLists文件中的文件。

更新

尝试遵循此question,我通过在#include "../src/stack.cpp"文件的末尾添加.h来修改文件,然后删除了src文件中的#include。这导致更多错误,即

stack.cpp:2:11: error: expected initializer before ‘<’ token
 void Stack<T>::push (T const& elem)
           ^
....

0 个答案:

没有答案