在 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 但将其放在命令行的末尾(顺序对库很重要)。