【问题标题】:c++17 `filesystem` is not a namespace-namec++17 `filesystem` 不是命名空间名称
【发布时间】:2018-06-27 00:05:54
【问题描述】:

我想知道为什么在下面的代码中,没有找到命名空间filesystem

g++ -std=c++17 main.cpp -lstdc++

// #include <filesystem>   <- error, so changed to the following:
#include <experimental/filesystem>

namespace fs = std::filesystem;

int main()
{
    return 0;
}

错误:

main.cpp:3:21: error: ‘filesystem’ is not a namespace-name
 namespace fs = std::filesystem;
                     ^
main.cpp:3:31: error: expected namespace-name before ‘;’ token
 namespace fs = std::filesystem;

gcc 版本 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)

【问题讨论】:

  • 如果您的编译器比您尝试使用的标准更旧,那么您可以期望的合规性就只有这么多。
  • std::filesystem 对 g++ 的支持从 8.0 版开始
  • 另外,为了能够链接,您必须将 -lstdc++fs 选项添加到 g++。请参阅en.cppreference.com/w/cpp/filesystem中的注释
  • g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0中对我来说很好

标签: c++ g++ std c++17


【解决方案1】:

GCC 5.4.0 于 2016 年 6 月发布;在采用 C++17 标准之前一年多。它及其版本的 libstdc++ 对 C++17 的支持非常有限。您可以看到 GCC 何时添加了 C++17 语言功能 here 以及 libstdc++ 何时添加了 C++17 标准库功能 here

在 GCC 5.4 发布时,文件系统库尚未在 std::filesystem 命名空间中实现。它与该版本中包含的任何其他 标头一起位于 std::experimental 命名空间中。

【讨论】:

  • 你知道有什么解决办法吗?
  • @SamZiggler 有什么解决方案吗?如果您必须使用旧的编译器,那么您必须包含适当的实验标头并使用std::experimental::filesystem。如果您想与各种编译器版本兼容,您可以使用一些预处理器检查来进行设置。
【解决方案2】:

&lt;experimental/..&gt; 表示实验命名空间:

namespace fs = std::experimental::filesystem;

见:http://en.cppreference.com/w/cpp/experimental/fs/path

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多