静态编译pthread

rul*_*501 2 c++ pthreads c++11

 Ruler501SabayonVM Rationals # g++ -static -static-libgcc -static-libstdc++
  -g -O0 -o obj/primitive --std=c++11 testcase.cpp -pthread
  && cd obj && ./primitive 8 

 terminate called after throwing an instance of 'std::system_error'  
 what():  Operation not permitted
 Aborted
Run Code Online (Sandbox Code Playgroud)

我在使用pthreads之前注意到了这个错误,但我正在连接它,所以我不认为我应该有这个错误.

我要在一台非常老的计算机上运行这个程序,我没有能力安装软件包,所以glibc版本根本不支持C++ 11,我用它来进行线程处理.

我遇到此错误的测试用例是

#include<iostream>
#include<thread>

void hello(){
    std::cout<< "Hello Concurrent World\n";
}
int main() {
    std::thread t(hello);
    t.join();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*ely 7

问题是libpthread没有被使用,所以真实pthread_create没有被链接,你的程序只调用pthread_createglibc中的存根,返回EPERM

解决方案是强制链接器使用libpthread中的所有符号,即使它认为不需要它们,这可以通过以下方式完成:

-Wl,--whole-archive -lpthread -Wl,--no-whole-archive
Run Code Online (Sandbox Code Playgroud)

(注意-lpthread不要-pthread)

  • 这是我见过的最快的接受时间.17秒! (2认同)