Compiler error with filesystem library: clang and g++

泪湿孤枕 提交于 2021-01-29 07:20:45

问题


I am writing a personal project in c++ which needs to access to files in some directories, hence I decided to use the filesystem library. I encountered some problems when I try to compile my project on MacOS and on Linux.

The code snippet is the following

#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;

}

When I compile it on my MacBook Pro (clang version 11.0.3 (clang-1103.0.32.62)) with

g++ -o test test.cpp -std=c++17 -Wall

everything works fine. But as soon as I move to Linux (Ubuntu 19.04, g++ 8.3.0) I get the following error:

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)){

I include then the filesystem library with #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;

}

compile it via g++ -o test test.cpp -std=c++17 -Wall -lstdc++fs and everything works fine on Linux too (note that I had to add -lstdc++fs).

Why is there this different behaviour on MacOS and on Linux? Does it depends on the compiler? What happens with Windows OS (I do not have any Windows PC at home)?


I found a related question and its answer here, but it does not seem to explain why in the first case (with clang) everything works fine also without including filesystem library.


回答1:


  1. Using 'g++' is not using clang you should use 'clang++'

  2. Gcc should not be platform dependent but it might be different version

  3. At any case, you should explicitly include header files needed, and std::filesystem is defined in "<filesystem>"

  4. regarding the need to add "lstdc++fs' - this is a hint that actually g++ version is different and uses different llvm versions. As described in https://en.cppreference.com/w/cpp/filesystem

Notes: Using this library may require additional compiler/linker options. GNU implementation prior to 9.1 requires linking with -lstdc++fs and LLVM implementation prior to LLVM 9.0 requires linking with -lc++fs



来源:https://stackoverflow.com/questions/64009875/compiler-error-with-filesystem-library-clang-and-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!