1

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

cigien
  • 57,834
  • 11
  • 73
  • 112
luyuan
  • 71
  • 1
  • 3
  • You could easily have edited your original [question](https://stackoverflow.com/questions/65335620) as you were advised to do, by simply adding the image. I'm quite confused by why you've posted a new question. It looks like more effort for no benefit. – cigien Dec 17 '20 at 08:25

1 Answers1

0

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • The bug report you linked is from 2012. I suppose I can respect their decision not to make `-static` work without further options, but I'm surprised they haven't at least documented it (as far as I can tell). Static linking seems like a fairly natural thing to want to do when appropriate, despite its tradeoffs, and the workaround isn't at all obvious. – Nate Eldredge Dec 18 '20 at 02:24
  • I had try -Wl,--whole-archive -lrt -lpthread -Wl,--no-whole-archive, I it worked on my Ubuntu-16.04, but still crashed on my embedded Linux. A good news, I got a useful fix,in my another questiom: https://stackoverflow.com/questions/65335620/terminate-called-after-throwing-an-instance-of-stdsystem-error/65348893#65348893 – luyuan Dec 19 '20 at 01:05