user149408
user149408

Reputation: 5881

CMake CHECK_FUNCTION_EXISTS for a function requiring #define

I a CMake project, I am trying to test for availability of pthread_setname_np(). As for the headers, this function prototype only seems to be exposed if I #define _GNU_SOURCE first.

Probably for this reason, simply doing

CHECK_FUNCTION_EXISTS(pthread_setname_np HAVE_PTHREAD_SETNAME_NP)

will not detect the function even though it is present. The documentation mentions CMAKE_REQUIRED_DEFINITIONS but I am not sure how to use it (nor if it is the right way at all).

How can I get CMake to correctly detect the presence of this function?

Upvotes: 2

Views: 1851

Answers (2)

user149408
user149408

Reputation: 5881

This eventually worked for me (at least on Ubuntu 18.04, currently running CI for others):

list(APPEND CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
list(APPEND CMAKE_REQUIRED_LIBRARIES pthread)
CHECK_SYMBOL_EXISTS(pthread_setname_np pthread.h HAVE_PTHREAD_SETNAME_NP)
list(REMOVE_ITEM CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)

Important: make sure you have a clean build environment, with no leftovers from previous builds. For cmake4eclipse, this means:

  • Go to Project > Properties > C/C++ Build > CMake and check Force CMake to run with each build. (You can clear that option again after your first successful build.)
  • Clean your project.

Appending the pthread library proved necessary for me, otherwise it would not detect the function. The library name seems to be pthreads on some systems (at least I see CMake testing for both); these systems may need further tweaks to detect the function.

CHECK_FUNCTION_EXISTS instead of CHECK_SYMBOL_EXISTS would have worked as well (I have tried both successfully).

Upvotes: 4

arrowd
arrowd

Reputation: 34401

Yes, CMAKE_REQUIRED_DEFINITIONS is a correct way to test for this function. Here's an example of its use:

set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
CHECK_FUNCTION_EXISTS(pthread_setname_np HAVE_PTHREAD_SETNAME_NP)
unset(CMAKE_REQUIRED_DEFINITIONS)

You also probably want to read this: What does “#define _GNU_SOURCE” imply?

Upvotes: 1

Related Questions