Search code examples
hyperlinkg++pthreadsldgoogletest

Why -pthread working but -lpthread does not?


I have successfully linked my simple gtest test with command g++ -o build/test1 build/test1.o -pthread -lgtest -lgtest_main

but i'm curios about options -pthread. Why it is not working with -lpthread as it working with -lgtest.

And why -gtest doest not working but -pthread without "l" is working...


Solution

  • In gcc, the -pthread flag is an indication to the compiler that it should set up things to allow for threaded code. I believe (but I'm not absolutely sure) that one of the things it does is add -lpthread so that the linker will use the relevant libraries when searching for unresolved symbols.

    However, it also does other things, like set -D_REENTRANT to specify the use of re-entrant code.

    In other words, -lpthread may not be enough on its own, since it only specifies that the threading library should be searched. I tend to use both to be certain that it does the right thing - yes, I am paranoid :-)