'std::filesystem::d irectory_iterator' 编译器问题

`std::filesystem::directory_iterator` compiler issue

本文关键字:编译器 iterator 问题 filesystem std irectory      更新时间:2023-10-16

很多人(例如 1、2(都问过如何让std::filesystem::directory_iterator工作,但我读完这些后仍然遇到麻烦。

我正在尝试构建一个小型静态库。将目录迭代器添加到一些源文件中后,我更新了我的 gcc,并添加了-lstdc++fs位,但似乎没有任何效果,因为我不断收到错误消息

fatal error: filesystem: No such file or directory
#include <filesystem>

如果我输入gcc --version,我得到

gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

如果我输入gcc-8 --version我会得到

gcc-8 (Ubuntu 8.1.0-1ubuntu1) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

这是我的小 shell 脚本,可以编译所有内容。我也尝试了其他一些变体。

EIGEN=/usr/include/eigen3
cd ./bin
for file in ../src/*cpp; do
g++ -std=c++11 -fPIC -c -I$EIGEN -I../include -O3 $file "-lstdc++fs"
done    
ar crv libfoo.a *.o
cd ..
<filesystem>

仅以 C++17 添加到C++标准库中。

g++ 7.3(您的默认g++(在此分数上不完全合规。它不会找到带有-std=c++17<filesystem>。 合理地,它不会找到带有-std=c++11<filesystem>,您发布的脚本要求它这样做。 但它会找到std=c++11或更晚的<experimental/filesystem>

你也有g++-8(大概是 g++ 8.1/8.2(。它将使用std=c++17定位<filesystem>

$ cat main.cpp 
#include <filesystem>
int main()
{
return 0;
}
$ g++-8 -std=c++17 main.cpp && echo $?
0

有趣的是,它也会对std=c++11std=c++14这样做:

$ g++-8 -std=c++11 main.cpp && echo $?
0
$ g++-8 -std=c++14 main.cpp && echo $?
0

使用g++-8,您无需将过渡库链接libstdc++fs

(顺便说一下,聪明的钱总是在编译中允许严格的警告:... -Wall -Wextra ...(