Is there a bug in GCC 7.3.0 link thread library use -static?

211 views Asked by At

I use std::call_once in my code, it compiled succeed but crashed when runing... like this demo:

#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;
}

Later I found,if i compiled with -static,it crashed,but run succeed just with -pthread or -lpthread: enter image description here

1

There are 1 answers

2
P.P On

std::call_once is implemented in libstdc++ on Linux using pthread_once. So you have to link with the pthread library to get its definition. See this thread for details. That's why -pthread becomes necessary. You can also see that using nm or objdump.

To be able to statically link pthread library, you need to ensure the all objects are linked in your binary. See this thread for details. Instead, you can include the whole archive with:

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

That should work as you want.

But note that, though there are some rare cases where static linking is useful, it's generally considered harmful.