g++ -Wl,--as-needed -pthread behaviour

Matthias Klose doko@ubuntu.com
Mon Sep 23 12:08:00 GMT 2013

With binutils from the 2.24 branch or trunk, the behaviour of --as-needed did
change, and what worked with binutils 2.23, now fails with 2.24:

$ cat thread.cpp
#include <thread>

void factorial(int n, unsigned long long int *result) {
        if (n==1) {
        for (; n!=0; n--) *result=*result*n;

int main() {
        unsigned long long int a;
        unsigned long long int *c=&a;
        std::thread t1(factorial,15,c);
        return 0;
$ ld --version
GNU ld (GNU Binutils for Ubuntu) 2.23.2
$ g++ -Wl,--as-needed -pthread thread.cpp -std=c++11 -o thread && ./thread

$ ld --version
GNU ld (GNU Binutils for Debian)
$ g++ -Wl,--as-needed -pthread thread.cpp -std=c++11 -o thread && ./thread
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted

So the test program doesn't have any direct references to symbols in libpthread,
and isn't linked, and fails to run.

According to the binutils maintainers, this behaviour is expected:


but it seems a bit odd that g++ -Wl,--as-needed -pthread isn't working anymore.


More information about the Gcc mailing list