Passing std::filesystem::path to a function segfaults

一曲冷凌霜 提交于 2019-11-28 12:48:00

I think the problem is that Ubuntu mixes GCC versions in a single installation. On Ubuntu the default GCC is version 8, but the libstdc++.so.6 library comes from GCC 9. With GCC 8 the std::filesystem definitions are in a separate library, libstdc++fs.a, which must be linked to explicitly. In GCC 9 the std::filesystem symbols are in the main libstdc++.so library. Because of the mixed up Ubuntu installation it's possible for the GCC 9 symbols in libstdc++.so to satisfy the undefined references in code compiled with GCC 8 which should be satisfied by libstdc++fs.a. Because the std::filesystem symbols in GCC 9 are incompatible with the experimental versions of those symbols in GCC 8, it appears to link OK but crashes at runtime.

It should work correctly if you make sure you link with -lstdc++fs and make sure that option comes after all your object files, e.g. this should work:

g++ foo.o bar.o -lstdc++fs

But this will not work:

g++ -lstdc++fs foo.o bar.o

There is supposed to be an update to the Ubuntu gcc-8 packages to fix this, by ensuring the -lstdc++fs option comes after all the other input files. For more details see https://bugs.launchpad.net/ubuntu/+source/gcc-8/+bug/1824721

Compiling with gcc-9 also works, because when using GCC 9 to compile there is no need to link to -lstdc++fs for std::filesystem (with GCC 9 it's only needed for std::experimental::filesystem symbols).

I was able to fix this issue by installing GCC and G++ 9 from this PPA: https://launchpad.net/~ubuntu-toolchain-r/+archive/ubuntu/test

Please link -lstdc++fs library, let's consider source file is fileSys.cpp then compile it as follows,
g++ -std=c++17 fileSys.cpp -lstdc++fs -o fs

I am using GCC 8.1.0 and Ubuntu 16.04.1 LTS.
There is already a similar question on this topic, you can find it at filesystem linker error

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