1

I have a project with a structure as follows.

.
├ 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) {
...
}

My cmake file is as follows

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}
)

It is more of a generic cmake rather than using the names exactly. The problem with this cmake file is that when i run it, the following error occurs.

[ 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

This clearly means that there is an error in linking but I am actually linking the file in cmakeLists file using target_link_libraries.

Update

Trying to follow this question, I modified the files by adding #include "../src/stack.cpp"in the end of .h file and then removed the #include in the src file. This resulted in more errors namely

stack.cpp:2:11: error: expected initializer before ‘<’ token
 void Stack<T>::push (T const& elem)
           ^
....
Community
  • 1
  • 1
Vinay Chandra
  • 502
  • 5
  • 18

0 Answers0