How to use fmt header only library without getting

2020-05-09 05:57发布

问题:

I'm trying to use the fmt (https://github.com/fmtlib/fmt) formatting header library in my c++ project.

I've added the path to the core header file at the top of my main file like so:

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

but when I try to call any function like:

string message = fmt::format("The answer is {}", 42);

I get the following error:

Undefined symbols for architecture x86_64:
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > fmt::v5::internal::vformat<char>(fmt::v5::basic_string_view<char>, fmt::v5::basic_format_args<fmt::v5::buffer_context<char>::type>)", referenced from:
      std::__1::basic_string<std::__1::enable_if<internal::is_string<char [17]>::value, fmt::v5::internal::char_t<char [17]>::type>::type, std::__1::char_traits<std::__1::enable_if<internal::is_string<char [17]>::value, fmt::v5::internal::char_t<char [17]>::type>::type>, std::__1::allocator<std::__1::enable_if<internal::is_string<char [17]>::value, fmt::v5::internal::char_t<char [17]>::type>::type> > fmt::v5::format<char [17], int>(char const (&) [17], int const&) 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)
make[2]: *** [main] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2

I'm not sure how to use this as this is how I have used other header libraries in the past such as cxxopts. Any help would be appreciated!

回答1:

You should link with the fmt library or use the optional header-only mode.

For example, if you have the file test.cc:

#include <fmt/core.h>

int main() {
  fmt::print("The answer is {}.", 42);
}

You can compile and link it with gcc:

g++ -std=c++11 test.cc -lfmt


标签: c++ fmt