-1

I don't know why error appears, i use target_link_libraries

c:/dev-tools/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles\submoduleTest1.dir/objects.a(main.cpp.obj):main.cpp:(.text.startup+0x2c): undefined reference to `void fmt_println2<char [5]>(char const (&) [5])'
collect2.exe: error: ld returned 1 exit status
mingw32-make[3]: *** [CMakeFiles\submoduleTest1.dir\build.make:101: submoduleTest1.exe] Error 1
mingw32-make[2]: *** [CMakeFiles\Makefile2:99: CMakeFiles/submoduleTest1.dir/all] Error 2
mingw32-make[1]: *** [CMakeFiles\Makefile2:106: CMakeFiles/submoduleTest1.dir/rule] Error 2
mingw32-make: *** [Makefile:123: submoduleTest1] Error 2

Main CMake:

cmake_minimum_required(VERSION 3.24)
project(submoduleTest1)


add_subdirectory(fmt_formatter)

set(CMAKE_CXX_STANDARD 17)

add_executable(submoduleTest1 main.cpp)
target_link_libraries(submoduleTest1 fmt_formatter)

fmt_formatter CMake:

find_package(fmt CONFIG REQUIRED)
add_library(fmt_formatter STATIC fmt_formatter.cpp fmt_formatter.h)
target_link_libraries(fmt_formatter fmt::fmt)

fmt_formatter.cpp

#include "fmt_formatter.h"

template<typename... Args>
void fmt_println(const fmt::text_style &ts, bool color, const Args &... args) {
    fmt::print(color ? ts : fmt::text_style(), args...);
    fmt::print("\n");
    fflush(stdout);
}

template<typename... Args>
void fmt_println2(const Args &... args) {
    fmt::print(fmt::text_style(), args...);
    fmt::print("\n");
    fflush(stdout);
}

fmt_formatter.h

#include "fmt/core.h"
#include "fmt/color.h"

template<typename... Args>
void fmt_println(const fmt::text_style &ts, bool color = true, const Args &... args);

template<typename... Args>
void fmt_println2(const Args &... args);

main.cpp

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

int main() {
    std::cout << "Hello, World!" << std::endl;
    fmt_println2("test");
    return 0;
}

Any ideas how can i solve it? I tried many solutions but any of them worked.

Kaspek
  • 159
  • 1
  • 11

1 Answers1

1

Move your template function definitions to the header file. For a template to be instantiated at compile time, the definition needs to be visible at that point, which it isn't if you put it in a cpp file and not the hpp file that gets included where the instantiation is happening.

For more info, see Why can templates only be implemented in the header file?

starball
  • 20,030
  • 7
  • 43
  • 238