问题描述

错误信息如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
../base/libbase_lib.a(memory_tool.cpp.o): In function `roobtyan::MemoryTool::MemoryTool()': 
/quick-dl-learning/learning/base/memory_tool.h:8: undefined reference to `std::filesystem::current_path[abi:cxx11]()'
../base/libbase_lib.a(memory_tool.cpp.o): In function `std::filesystem::__cxx11::path::operator/=(std::filesystem::__cxx11::path const&)':
/usr/include/c++/8/bits/fs_path.h:258: undefined reference to `std::filesystem::__cxx11::path::has_filename() const'
/usr/include/c++/8/bits/fs_path.h:261: undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'
../base/libbase_lib.a(memory_tool.cpp.o): In function `std::filesystem::__cxx11::path::is_absolute() const':
/usr/include/c++/8/bits/fs_path.h:381: undefined reference to `std::filesystem::__cxx11::path::has_root_directory() const'
../base/libbase_lib.a(memory_tool.cpp.o): In function `std::filesystem::__cxx11::path::path<char [16], std::filesystem::__cxx11::path>(char const (&) [16], std::filesystem::__cxx11::path::format)':
/usr/include/c++/8/bits/fs_path.h:185: undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
learning/provider/CMakeFiles/learning.dir/build.make:137: recipe for target 'learning/provider/learning' failed
make[2]: *** [learning/provider/learning] Error 1
CMakeFiles/Makefile2:5113: recipe for target 'learning/provider/CMakeFiles/learning.dir/all' failed
make[1]: *** [learning/provider/CMakeFiles/learning.dir/all] Error 2
Makefile:155: recipe for target 'all' failed
make: *** [all] Error 2

环境

  • Ubuntu 18.04
  • CMake 3.20
  • g++-8

cmake配置

1
2
3
4
5
cmake_minimum_required(VERSION 3.20)
project(learning)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

问题原因

这是链接阶段引发的问题,编译阶段没有问题。
由于filesystem是C++17中引入的新特性,处于实验阶段,未集成到标准库,因此需要在cmake中手动链接

1
target_link_libraries(learning stdc++fs)

在gcc9或者更高的版本中,已经完全包含,所以无需手动链接。