PDA

View Full Version : How do I include -lpthread (or other g++ args) in a CMake project?



WhiteHotLoveTiger
11th November 2013, 22:29
Earlier today I was trying to get my project to compile with the g++ option, "-std=c++11". Being new to both Qt Creator & CMake, I thought that the place to put this option was under Tools -> Options -> Build & Run -> Compilers -> Platform codegen flags. I quickly found out that this isn't where it goes, and after some searching, learned that I should adding this to my CMakeLists.txt: "ADD_DEFINITIONS( -std=c++11 )". Good enough.

Now, I'm trying to add the g++ option, "-lpthread". This time, I tried adding in CMakeLists.txt like this: "ADD_DEFINITIONS( -std=c++11 -lpthread)". This didn't do the trick, so I tried adding "-pthread" in Tools -> Options -> Build & Run -> Compilers -> Platform linker flags. This didn't work for me either.

Where should I be trying to add this option? :confused:

Thanks.

ChrisW67
12th November 2013, 04:47
Seems to me you want:


target_link_libraries(<targetname> lib1 lib2 ...)

e.g.
target_link_libraries( MyCoolApp pthread )

You should check the CMake Qt support is not already adding this as qmake does for a build on Linux.

KShots
18th November 2013, 18:44
Also, a better solution for enabling C++11 on gcc under CMake is the following:
if(CMAKE_COMPILER_IS_GNUCC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
endif(CMAKE_COMPILER_IS_GNUCC)On a fun note, I also tend to add the following to all my CMake projects:
option(enable_maintainer "Enables the maintainer CFLAGS (-Wall -Werror)" OFF)
if(enable_maintainer)
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror")
endif(CMAKE_COMPILER_IS_GNUCXX)
endif(enable_maintainer)... which essentially means that any compiler warnings will show up as errors and demand to be fixed before things will actually compile... but it's turned off by default, so people don't accidentally turn it on.
Fully concur with ChrisW67's advice on target_link_libraries command for including the pthread library. He's right, though - if your project is using Qt at all (not clear from your post), then the pthread library is likely already being pulled in as a dependency of QtCore, and you shouldn't need to pull it in with any further calls in CMakeLists.txt.

kelqi
6th March 2019, 15:54
I am having the same problem, do you have a solution if so please share!
Thank you in advance!

KShots
6th March 2019, 20:57
Which problem, specifically? Including pthreads support or including C++11 support? pthreads is discussed above... I'd recommend against following the above (outdated) advice for C++11, though... cmake has since integrated C++11 (and later) compiler features into the build tool so it's not tied to a specific compiler - it should check for the features you're using for any given compiler.