Basics: std::thread on Linux with CMake

Basics: std::thread on Linux with CMake

Life is not easy as a multi-platform developer. This was the main reason for projects like VISlib and the now dead and buried TheLib. But times have changed. The new C++11 standard brought in some very nice and useful classes. Maybe the only thing I really miss right now is IPC, RPC and fundamentally sockets. However, the new threading classes are very nice, like, of course, std::thread.

Well, I am a Windows-software developer. And I continuously port my code to the other platforms, like Linux and sometimes OS X. Thus, there are always some issues when doing something for the first time. For example, when I tried to build my first test program for std::thread unter Ubuntu, I got the std::exception:

Operation not permitted

Well, of course, I linked against pthread. But something must have gone wrong. I asked the almighty Internet, and of course StackOverflow answered:

In short words: It was an issue of the ordering of the arguments to Gcc, which in my opinion is one of the most annoying issues with the Gcc.

This does not work:

g++ -std=c++0x -lpthread -o test ./test.cpp

This does work:

g++ -std=c++0x -o test ./test.cpp -lpthread

User user405725 nicely summarized it in his comment:

You generally have to specify libraries AFTER object files or they are not pulled in.

Ok. So what about CMake: StackOverflow:

The different possibilities may also result in different parameter ordering. Following the formal way and using find_package:

cmake_minimum_required (VERSION 2.6)
find_package (Threads)
add_executable (myapp main.cpp ...)
target_link_libraries (myapp ${CMAKE_THREAD_LIBS_INIT})

everything works like it should be.

However, if I try to take the short way out, e.i. by specifying the arguments directly, like:

SET(CMAKE_CXX_FLAGS_DEBUG "... -lpthread")

on my Ubuntu installation with my Gcc I ended up with the wrong ordering of arguments and my test program failed.

I like Cmake. I works. But you should not try to enforce your way of doing things if it is against the way of CMake used to do things. It will work up to some degree, but you will get problems going beyond that point. Just follow the way of CMake and, most of the time, everything will work.

1 Comment on “Basics: std::thread on Linux with CMake

  1. With more up-to-date cmake versions (meaning >3.0) it’s better to use modern cmake-syntax like e.g.:

    find_package(Threads REQUIRED)
    target_link_libraries(myapp PRIVATE Threads::Threads)

    Then you usually don’t have to worry anymore about cmake variable, linker flags and so on.

    PS: I hope some form of markdown works here in this blog…

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.