【问题标题】:How to avoid std::filesystem linker errors with Qt?Qt 如何避免 std::filesystem 链接器错误?
【发布时间】:2019-08-14 13:55:20
【问题描述】:

我想将 std::filesystem 与 Qt 5.12.0 与 g++ 版本 Ubuntu 8.2.0-7ubuntu1 一起使用,但出现链接器错误:

g++ -lstdc++fs -Wl,-rpath,/home/user/Qt/5.12.0/gcc_64/lib -o qf_filesystem_test main.o   -L/home/user/Qt/5.12.0/gcc_64/lib -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread   
/usr/bin/ld: main.o: in function `std::filesystem::exists(std::filesystem::__cxx11::path const&)':
/usr/include/c++/8/bits/fs_ops.h:121: undefined reference to `std::filesystem::status(std::filesystem::__cxx11::path const&)'
/usr/bin/ld: main.o: in function `std::filesystem::__cxx11::path::path<char*, std::filesystem::__cxx11::path>(char* const&, std::filesystem::__cxx11::path::format)':
/usr/include/c++/8/bits/fs_path.h:183: undefined reference to `std::filesystem::__cxx11::path::_M_split_cmpts()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:257: qf_filesystem_test] Error 1
22:12:16: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project qf_filesystem_test (kit: Desktop Qt 5.12.0 GCC 64bit)
When executing step "Make"

经过一番谷歌搜索,我发现我需要使用链接器标志-lstdc++fs。我的代码使用命令g++ main.cpp -std=c++17 -lstdc++fs 完美构建,但我似乎无法使其在Qt Creator 中工作。我的简单测试代码如下:

#include <iostream>
#include <filesystem>

int main(int argc, char *argv[])
{
    if(1 < argc)
    {
        std::cout << argv[1] << " does ";
        if(!std::filesystem::exists(std::filesystem::path(argv[1]))) std::cout << "not ";
        std::cout << "exist!" << std::endl;
    }

    return 0;
}

我的 .pro 文件如下所示:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = qf_filesystem_test
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

CONFIG += c++17
QMAKE_LFLAGS += -lstdc++fs

SOURCES += main.cpp

在使用 g++ 进行一些测试后,在我看来,问题是由 g++ 标志的顺序引起的,因为 Qt 将 -lstdc++fs 放在了前面。

  • 为什么我还需要使用这个标志?我认为 g++8 已经支持 C++17,只有当我想使用 std::experimental::filesystem 时才需要这个标志。
  • 如何在 Qt Creator 中构建代码?

【问题讨论】:

  • 将您的 CONFIG += c++17 更改为 CONFIG += C++1z
  • 它没有帮助,仍然存在相同的链接器错误。

标签: qt g++ c++17 std-filesystem


【解决方案1】:

&lt;filesystem&gt; 是 GCC 8 (see this question) 的独立库。正如您所怀疑的,您的问题是标志的顺序。在文档中戳了一下暗示QMAKE_LFLAGS 更多地用于链接器标志而不是库加载,这就是它提前通过的原因(例如-O3)。

使用LIBS += -lstdc++fs 应该可以代替。

感谢 this reddit response 提供此解决方案。

【讨论】:

    猜你喜欢
    • 2012-10-06
    • 1970-01-01
    • 2011-06-06
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多