Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue on build {fmt} with CMake

Tags:

c++

cmake

fmt

I have a issue on build {fmt} with CMake.

The structure of a project is the following:

.
├── CMakeLists.txt
├── dep
│   └── fmt
└── src
    ├── CMakeLists.txt
    └── main.cpp

./CMakeLists.txt is the following:

cmake_minimum_required(VERSION 3.2)
project(fmtdemo)
add_subdirectory(dep/fmt)
add_subdirectory(src)

./src/CMakeLists.txt is the following:

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 is the following:

#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;
}

When I build it I receive an error:

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
like image 223
Haoshen Zhong Avatar asked Dec 12 '25 14:12

Haoshen Zhong


1 Answers

You should link with fmt, not fmt-header-only:

target_link_libraries(fmtdemo PUBLIC fmt::fmt)

Or if you want to use the header-only configuration, make sure to include the fmt/format.h header instead of fmt/core.h. The latter provides a subset of the API for faster compilation and requires linking with the fmt library.

like image 138
vitaut Avatar answered Dec 15 '25 08:12

vitaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!