gcc arguments: -pthread. What does it do?

1.8k views Asked by At

I'm getting started with multi-thread programming using gcc under Debian 8. I've successfully written and run a multi-threaded test app (foobar.c), but I'm confused by the Makefile (copied from an example). In particular, the command that works is

gcc foobar.c -o foobar -pthread

I'm confused by "-pthread". is that

(a) an option "-p" with value "thread", or
(b) an argument "-pthread" ?

if either case, what is it actually doing? Including some library? Including some object? Setting some other option?

BTW - A similar question 15929739 was asked but never answered. Question 20924412 was not helpful either.

1

There are 1 answers

1
Jonathon Reinhart On BEST ANSWER

From the man page:

-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.

To be specific, as of GCC 6.2.1, -pthread will:

  • #define _REENTRANT 1
  • Add -lpthread to link against libpthread

How do I know this, you ask?

What preprocessor flags are added?

Let's dump the preprocessor defines and compare them:

$ diff <(gcc -dM -E - < /dev/null) <(gcc -pthread -dM -E - < /dev/null)
> #define _REENTRANT 1

What linker options are added?

Let's dump the ld options passed by GCC and compare them:

diff <(gcc -### -o foo empty.c 2>&1) <(gcc -### -pthread -o foo empty.c 2>&1)

The output here is a bit more verbose, but if we ignore the temporary filename differences, we find:

  • -lpthread
  • "-plugin-opt=-pass-through=-lpthread"