What is the difference between gcc -pthread
and gcc -lpthread
which is used while compiling multithreaded programs?
Compiling is the general term for taking source code written in one language and transforming into another. Transpiling is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction.
Compile time is the period when the programming code (such as C#, Java, C, Python) is converted to the machine code (i.e. binary code). Runtime is the period of time when a program is running and generally occurs after compile time.
Compiling - The modified source code is compiled into binary object code. This code is not yet executable. Linking - The object code is combined with required supporting code to make an executable program. This step typically involves adding in any libraries that are required.
The expanded source code is passed to the compiler, and the compiler converts this expanded source code into assembly code. The extension of the assembly code would be hello. s. This assembly code is then sent to the assembler, which converts the assembly code into object code.
-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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With