我在使用 CMake 构建 {fmt} 时遇到问题。
一个项目的结构如下:
.
├── CMakeLists.txt
├── dep
│ └── fmt
└── src
├── CMakeLists.txt
└── main.cpp
./CMakeLists.txt
如下:
cmake_minimum_required(VERSION 3.2)
project(fmtdemo)
add_subdirectory(dep/fmt)
add_subdirectory(src)
./src/CMakeLists.txt
如下:
project(fmtdemo)
add_library(fmtdemo main.cpp)
add_library(fmtdemo::fmtdemo ALIAS fmtdemo)
target_link_libraries(fmtdemo PUBLIC fmt::fmt-header-only)
add_executable(fdemo main.cpp)
./src/main.cpp
如下:
#include "../dep/fmt/include/fmt/core.h"
using namespace std;
int main()
{
fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
string message = fmt::format("The answer is {}", 42);
return 0;
}
当我构建它时,我收到一个错误:
CMakeFiles/fdemo.dir/main.cpp.o: In function `void fmt::v5::print<char [30], double, 0>(char const (&) [30], double&&)':
main.cpp:(.text._ZN3fmt2v55printIA30_cJdELi0EEEvRKT_DpOT0_[_ZN3fmt2v55printIA30_cJdELi0EEEvRKT_DpOT0_]+0x78): undefined reference to `fmt::v5::vprint(fmt::v5::basic_string_view<char>, fmt::v5::format_args)'
CMakeFiles/fdemo.dir/main.cpp.o: In function `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > fmt::v5::format<char [17], int, char>(char const (&) [17], int&&)':
main.cpp:(.text._ZN3fmt2v56formatIA17_cJiEcEENSt7__cxx1112basic_stringIT1_St11char_traitsIS5_ESaIS5_EEERKT_DpOT0_[_ZN3fmt2v56formatIA17_cJiEcEENSt7__cxx1112basic_stringIT1_St11char_traitsIS5_ESaIS5_EEERKT_DpOT0_]+0x7f): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >
fmt::v5::internal::vformat<char>(fmt::v5::basic_string_view<char>, fmt::v5::basic_format_args<fmt::v5::basic_format_context<std::back_insert_iterator<fmt::v5::internal::buffer<char> >, char> >)'
collect2: error: ld returned 1 exit status
src/CMakeFiles/fdemo.dir/build.make:83: recipe for target 'src/fdemo' failed
make[2]: *** [src/fdemo] Error 1
CMakeFiles/Makefile2:170: recipe for target 'src/CMakeFiles/fdemo.dir/all' failed
make[1]: *** [src/CMakeFiles/fdemo.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2