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:
std::call_once
is implemented in libstdc++ on Linux usingpthread_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 usingnm
orobjdump
.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:
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.