Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

multithreading - Difference between -pthread and -lpthread while compiling

What is the difference between gcc -pthread and gcc -lpthread which is used while compiling multithreaded programs?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

$ 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 -lpthread option only causes the pthread library to be linked - the pre-defined macros don't get defined.

Bottom line: you should use the -pthread option.


Note: the -pthread option 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.

Also note that other similar options have been used by GCC, such as -pthreads (listed as a synonym for -pthread on 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 -pthread uniformly going forward.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...