0

So I am trying to build a library with CMake that I have written myself. It looks a bit messy but here is the top-level (with only the troublesome lines) CMakeLists.txt file

add_subdirectory(src/MadiMat)
 add_library(MadiMat)
 target_sources(MadiMat PUBLIC src/MadiMat/MadiMat.cpp src/MadiMat/MadiMat.hpp)
 target_include_directories(MadiMat PUBLIC src/MadiMat)
    set_target_properties(MadiMat PROPERTIES
  PUBLIC_HEADER ${CMAKE_SOURCE_DIR}/src/MadiMat.hpp
)
    target_compile_features(MadiMat PUBLIC cxx_std_20)


    add_executable(runMadi ${CMAKE_SOURCE_DIR}/src/main.cpp)
    target_link_libraries(runMadi LINK_PUBLIC MadiMat)

(nothing too fancy, just a simple project to learn CMake features). However, when I try to run the make command it prints me this when I try to use the PrintVec function I defined in my cpp file:

Undefined symbols for architecture x86_64:
  "__ZN18MadiFEMLinearSpace7MadiVecIdE8PrintVecEv", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make[2]: *** [runMadi] Error 1
make[1]: *** [CMakeFiles/runMadi.dir/all] Error 2
make: *** [all] Error 2

everything works well when this function is put in the .hpp file but as .cpp are implementation files it should not but this way. Anyway, as I am new to this, I might have done something silly. Don't hesitate if you need more info.

I have tried to find solutions on Internet but none could solve this particular problem.

Edit : here is the code in MadiMat.cpp. dummy.cpp is just a dummy cpp file to avoid some warnings from cmake there is nothing inside.

#include "MadiMat.hpp"
#include "dummy.cpp"
#include <iostream>

template <typename T> // Printing vector
inline void MadiFEMLinearSpace::MadiVec<T>::PrintVec() {
  for (auto elem : _Vec) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;
}
  • Defining a **templated** function in a separate compilation unit requires more steps than defining regular, non-templated functions. See [duplicate question](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) for more details. – Tsyvarev May 26 '23 at 13:56

0 Answers0