我们都知道, pthread 是 POSIX 的 thread 库, 各种 Unix 系统中的多线程多是基于它的。 对于 C/C++ 代码, 用到 pthread 库的, 也要链接它。 而 gcc 链接其他库的选项就是 -l 后接库名。 所以, 链接 pthread 库的命令是 -lpthread 了。
但是, 也经常会见到有代码使用了 -pthread 的选项, 用这个选项替换 -lpthread 也能正常工作。 那么它们是一样的么? 应该选择哪个?
在 gcc 的 Option Summary 页面里对这个选项没有详细的说明, 其实它在 man gcc 里:
-pthread
Add support for multithreading using the POSIX threads library. This option sets flags for both the preprocessor and linker. It does not affect the thread safety of object code produced by the compiler or that of libraries supplied with it. These are HP-UX specific flags.
所以简单的说, -pthread 也同样会链接 pthread 库, 而不同的是, 它还会设置一些 pthread 相关的宏, 比如 _REENTRANT 、 __USE_REENTRANT 等。所以呢, 除非有特别的原因, -pthread 比 -lpthread 更值得推荐。
事实上, 还有第三个选项, -pthreads , 仅在 Solaris 上有效, 和 -pthread 效果一样。

这也是我前几天回答的一个问题, “阅读原文”指向此问题。