I'm compiling a project that has several header files, one of them is a general "utils" file with general-purpose functions.
When I include the header file for this utils file, compilation fails (see error below), but when I include the actual .cpp file, it works.
I am using a CMakeLists.txt file with CLion, on MacOS High Sierra.
A minimal equivalent project that fails in the same way:
main.cpp:
#include "util.h"
int main() {
print("Hello");
return 0;
}
util.h:
#pragma once
#include <string>
#include <iostream>
#include <sstream>
template<typename T>
void print(T thing_to_print);
util.cpp:
#include "util.h"
template <typename T>
void print(T thing_to_print){
std::cout << thing_to_print << std::endl;
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.7)
project(example)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_VERBOSE_MAKEFILE ON)
SET(UTILS_MINIMAL_LIB_FILES util.h util.cpp)
add_library(utils_lib_minimal ${UTILS_MINIMAL_LIB_FILES})
add_executable(main_test main.cpp)
target_link_libraries(main_test utils_lib_minimal)
Build fails:
Undefined symbols for architecture x86_64:
"void print<char const*>(char const*)", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
However, when I change the include statement to :
#include "util.cpp"
The compilation completes successfully.
Any ideas? Thanks in advance.