微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 aarch64 中使用 pthread 编译时出现 ld 错误

如何解决在 aarch64 中使用 pthread 编译时出现 ld 错误

我正在尝试使用基于 aarch64 的 linux 主机上的线程编译和链接一个简单的 C++ 程序。简单的程序如下:

#include <iostream>
#include <thread>
#include <atomic>

using namespace std;

#define IteraTIONS 1000

// to be called for multi threaded execution
void increment_atomic_thread (atomic<int>& a)
{
    for (int i = 0; i < IteraTIONS; i++)
    {
        a++;
    }
}

int main (int argc,char* argv[])
{ 
    atomic<int> a,b,c,d;

    thread t1 ( [&]() { increment_atomic_thread(a); } );
    thread t2 ( [&]() { increment_atomic_thread(b); } );
    thread t3 ( [&]() { increment_atomic_thread(c); } );
    thread t4 ( [&]() { increment_atomic_thread(d); } );

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    return 0;
}

这段代码在 x86-64 机器上编译得很好,但是我在 aarch64 机器上遇到如下 ld 错误(使用 --verbose 编译时输出是最后几行):

attempt to open /usr/lib/gcc/aarch64-linux-gnu/7/../../../aarch64-linux-gnu/crtn.o succeeded
/usr/lib/gcc/aarch64-linux-gnu/7/../../../aarch64-linux-gnu/crtn.o
libm.so.6 needed by /usr/lib/gcc/aarch64-linux-gnu/7/libstdc++.so
found libm.so at /usr/lib/gcc/aarch64-linux-gnu/7/../../../aarch64-linux-gnu/libm.so
/usr/bin/ld: /usr/lib/aarch64-linux-gnu/libpthread.a(pthread_create.o): relocation R_AARCH64_ADR_PREL_PG_HI21 against symbol `__stack_chk_guard@@GLIBC_2.17' which may bind externally can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: /usr/lib/aarch64-linux-gnu/libpthread.a(pthread_create.o)(.text+0x9cc): unresolvable R_AARCH64_ADR_PREL_PG_HI21 relocation against symbol `__stack_chk_guard@@GLIBC_2.17'
/usr/bin/ld: final link Failed: Bad value
collect2: error: ld returned 1 exit status

编译命令为:

g++ -g -std=c++17 -lpthread -Xlinker --verbose -o pthread_basic.app pthread_basic.cpp /usr/lib/aarch64-linux-gnu/libpthread.a

解决方法

谢谢@Some programmer 伙计。在此处粘贴 his comment

您不需要同时需要 -lpthread/usr/lib/aarch64-linux-gnu/libpthread.a。消除 最后一个并保留 -lpthread 但将其放在命令行的末尾(顺序对库很重要)。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。