multithreading 编译时 -pthread 和 -lpthread 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23250863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 01:25:23  来源:igfitidea点击:

Difference between -pthread and -lpthread while compiling

multithreadinggccthread-safetypthreadscompiler-flags

提问by Vishnuraj V

What is the difference between gcc -pthreadand gcc -lpthreadwhich is used while compiling multithreaded programs?

编译多线程程序时使用的gcc -pthreadgcc -lpthread有什么区别?

回答by Michael Burr

-pthreadtells the compiler to link in the pthread library as well as configure the compilation for threads.

-pthread告诉编译器链接 pthread 库并配置线程的编译。

For example, the following shows the macros that get defined when the -pthreadoption gets used on the GCC package installed on my Ubuntu machine:

例如,以下显示了-pthread在我的 Ubuntu 机器上安装的 GCC 包上使用该选项时定义的宏:

$ gcc -pthread -E -dM test.c > dm.pthread.txt
$ gcc          -E -dM test.c > dm.nopthread.txt
$ diff dm.pthread.txt dm.nopthread.txt 
152d151
< #define _REENTRANT 1
208d206
< #define __USE_REENTRANT 1

Using the -lpthreadoption only causes the pthread library to be linked - the pre-defined macros don't get defined.

使用该-lpthread选项只会导致链接 pthread 库 - 未定义预定义的宏。

Bottom line: you should use the -pthreadoption.

底线:您应该使用该-pthread选项。



Note: the -pthreadoption is documented as a platform specific option in the GCC docs, so it might not always be available. However, it is available on platforms that the GCC docs don't explicitly list it for (such as i386 and x86-64) - you should use it when available.

注意:该-pthread选项在 GCC 文档中被记录为特定于平台的选项,因此它可能并不总是可用。但是,它在 GCC 文档未明确列出的平台上可用(例如 i386 和 x86-64)——您应该在可用时使用它。

Also note that other similar options have been used by GCC, such as -pthreads(listed as a synonym for -pthreadon Solaris 2) and -mthread(for MinGW-specific thread support on i386 and x86-64 Windows). My understanding is that GCC is trying to move to using -pthreaduniformly going forward.

另请注意,GCC 还使用了其他类似的选项,例如-pthreads-pthread在 Solaris 2 上列为的同义词)和-mthread(用于 i386 和 x86-64 Windows 上的 MinGW 特定线程支持)。我的理解是 GCC 正试图转向-pthread统一使用。

回答by Praveen Kumar

-pthreadAdds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker (man gcc).

-pthread使用 pthreads 库添加对多线程的支持。此选项为预处理器和链接器 ( man gcc)设置标志。

while

尽管

-lpthreadcomes in existence while linking there will be no influence while preprocessing.

-lpthread链接时存在,预处理时没有影响。