【问题标题】:Is there a bug in GCC 7.3.0 link thread library use -static? [duplicate]GCC 7.3.0 链接线程库使用 -static 是否存在错误? [复制]
【发布时间】:2021-03-27 22:07:18
【问题描述】:

我在我的代码中使用了 std::call_once,它编译成功但在运行时崩溃了... 喜欢这个演示:

#include <iostream>
#include <mutex>
using namespace std;

int main()
{
    cout << "Hello world" << endl;
    static once_flag of;
    call_once(of,[]{});
    cout << "see you again" << endl;

    return 0;
}

后来我发现,如果我用 -static 编译,它会崩溃,但只用 -pthread 或 -lpthread 运行成功:

【问题讨论】:

  • 您可以按照建议的方式轻松编辑原始question,只需添加图像即可。我对你为什么发布一个新问题感到很困惑。看起来更多的努力没有任何好处。

标签: c++ c++11 pthreads std gcc7


【解决方案1】:

std::call_once 在 Linux 上的 libstdc++ 中使用pthread_once 实现。所以你必须链接 pthread 库来获得它的定义。 See this thread for details。这就是为什么-pthread 变得必要的原因。您还可以使用nmobjdump 来查看。

为了能够静态链接 pthread 库,您需要确保所有对象都链接到您的二进制文件中。 See this thread for details。 相反,您可以包含整个存档:

g++ std_callonce.cpp -g -static -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

这应该可以如你所愿。

但请注意,虽然在少数情况下静态链接很有用,但通常是considered harmful

【讨论】:

  • 您链接的错误报告来自 2012 年。我想我可以尊重他们在没有其他选择的情况下不让 -static 工作的决定,但我很惊讶他们至少没有记录它(如据我所知)。静态链接似乎是在适当的时候想要做的一件相当自然的事情,尽管它需要权衡取舍,而且解决方法一点也不明显。
  • 我尝试过 -Wl,--whole-archive -lrt -lpthread -Wl,--no-whole-archive,它在我的 Ubuntu-16.04 上运行,但在我的嵌入式 Linux 上仍然崩溃.一个好消息,在我的另一个问题中,我得到了一个有用的修复:stackoverflow.com/questions/65335620/…
猜你喜欢
  • 2018-10-17
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多