- 此问题在此处已有答案**:
(17个答案)
2天前关闭。
我不知道为什么会出现错误,我使用了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
主要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_格式化程序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;
}
有什么想法我怎么才能解决它?我试过很多解决方案,但都不管用。
1条答案
按热度按时间5vf7fwbs1#
把你的模板函数定义移到头文件中,对于一个在编译时示例化的模板,定义需要在那一点上可见,如果你把它放在cpp文件中而不是hpp文件中,那么它就不是可见的。
有关详细信息,请参见Why can templates only be implemented in the header file?