Clang++中C++11 thread的支持

问题

在Ubuntu中使用Clang++,

1
clang++-3.7 -std=c++11 test.cpp

编译C++11编写的多线程代码时,

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <thread>

void f()
{
std::cout << "Hello World\n";
}

int main()
{
std::thread t(f);
t.join();
}

发现如下问题:

1
2
3
/tmp/test-9606ba.o: In function `std::thread::thread<void (&)()>(void (&)())':
test.cpp:(.text[_ZNSt6threadC2IRFvvEJEEEOT_DpOT0_]+0x21): undefined reference to `pthread_create'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

分析

  1. 在Linux中,Standard C++ library的默认实现是libstdc++。虽然安装了clang,但是编译时使用的仍然是GNU的libstdc++。

  2. 执行clang++ -v以后,可以知道使用的线程模型是posix。

解决

既然底层使用了posix来实现C++11的线程,那么编译的时候必然要有-pthread

1
clang++-3.7 -std=c++11 -pthread test.cpp