【发布时间】:2020-09-22 12:36:39
【问题描述】:
我正在用 c++ 编写一个个人项目,它需要访问某些目录中的文件,因此我决定使用filesystem 库。当我尝试在 MacOS 和 Linux 上编译我的项目时遇到了一些问题。
代码sn-p如下
#include <iostream>
#include <fstream>
int main(){
std::string path = "Inner";
std::cout << "Files in " << path << " directory :" << std::endl;
for (const auto & entry : std::filesystem::directory_iterator(path))
std::cout << entry.path() << std::endl;
return 0;
}
当我在我的 MacBook Pro(clang 版本 11.0.3 (clang-1103.0.32.62))上使用
g++ -o test test.cpp -std=c++17 -Wall
一切正常。但是,一旦我迁移到 Linux(Ubuntu 19.04,g++ 8.3.0),我就会收到以下错误:
test.cpp: In function ‘int main()’:
test.cpp:8:33: error: ‘std::filesystem’ has not been declared
for (const auto & entry : std::filesystem::directory_iterator(path)){
然后我将文件系统库包含在#include <filesystem>:
#include <iostream>
#include <fstream>
#include <filesystem>
int main(){
std::string path = "Inner";
std::cout << "Files in " << path << " directory :" << std::endl;
for (const auto & entry : std::filesystem::directory_iterator(path))
std::cout << entry.path() << std::endl;
return 0;
}
通过g++ -o test test.cpp -std=c++17 -Wall -lstdc++fs 编译它,在Linux 上一切正常(注意我必须添加-lstdc++fs)。
为什么在 MacOS 和 Linux 上会有这种不同的行为?它取决于编译器吗? Windows 操作系统会发生什么(我家里没有任何 Windows PC)?
我找到了一个相关问题及其答案here,但它似乎无法解释为什么在第一种情况下(使用 clang)在不包括 filesystem 库的情况下一切正常。
【问题讨论】:
-
C++ 标准允许标准头文件包含来自其他标准头文件的声明。我想在第一种情况下,
<fstream>标头还包括部分或全部文件系统声明。 -
我知道这个问题有很好的重复,但似乎找不到它们。无论如何,简短的解决方案:始终明确包含您使用的功能所需的头文件。 A good reference 帮助确定需要哪些标头。
-
@john 我认为
-std=c++17我将编译设置为使用相同的标准,但显然我错了。 -
@Eddymage 您使用的是相同的标准。只是标准有一定的灵活性,不同的编译器会做出不同的选择。
-
@Someprogrammerdude 是的,你是对的,我总是检查this,但在文件系统库页面中我找不到任何关于我的问题的线索,也没有在底部的注释中找到。