Difference between -pthread and -lpthread while compiling

后端 未结 3 1959
面向向阳花
面向向阳花 2020-11-22 14:23

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

3条回答
  •  臣服心动
    2020-11-22 14:40

    There is an accepted answer, but, IMO, it doesn't provide enough context and insight. Hence this extra answer.


    -lpthread is a solution for a problem that no longer exists (since ~2005).

    In the old days there were proprietary implementations of Pthreads API that weren't POSIX-compliant, like LinuxThreads. POSIX standard merely says that if one wants POSIX-compliant behaviour, then one must link with -lpthread, and linking that is required to link a POSIX-compliant implementation of Pthreads API, should there be many implementations of it.

    There are no multiple implementations of Pthreads API in modern operating systems. And that is why -lpthread no longer serves any purpose.


    Compilers like gcc and clang (and, probably, all Linux-compatible compilers) require using -pthread command line option for both compiling and linking POSIX-compliant multi-threaded applications and that is what one must use.

    At compile time, -pthread option manifests that Pthread API is requested (there can be multiple threading APIs, e.g. Solaris Threads) and defines platform-specific macros (_REENTRANT on Linux, _MT on Solaris).

    At link time, -pthread links in required libraries (if any) that implement POSIX-compliant Pthreads API behaviour.

    The above makes it clear why -lpthread is neither necessary nor sufficient.

提交回复
热议问题