1

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.

Nur L
  • 791
  • 7
  • 15
  • 3
    You might move implementations of templates to header file. [Why can templates only be implemented in the header file?](https://stackoverflow.com/q/495021/3309790) – songyuanyao Apr 26 '18 at 08:52
  • Thanks so much @songyuanyao, that is indeed the solution. Please feel free to post as an answer so I can mark it as such. – Nur L Apr 26 '18 at 09:03
  • 1
    Well if that's the solution then the question should be marked as duplicated, as @molbdnilo did. :) – songyuanyao Apr 26 '18 at 09:08

0 Answers0