Why doesn't CHECK_FUNCTION_EXISTS find clock_g

2019-04-26 15:04发布

How come CHECK_FUNCTION_EXISTS doesn't find clock_gettime?

I use the following code in my CMakeLists.txt:

include(CheckFunctionExists)

set(CMAKE_EXTRA_INCLUDE_FILES time.h)
CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)

This is on a POSIX system I know has clock_gettime. Yet I simply get:

-- Looking for clock_gettime - not found

标签: c cmake
2条回答
Bombasti
2楼-- · 2019-04-26 15:44

Because clock_gettime is found in librt we need to link to that when doing the check (otherwise CMake will simply fail to compile the test program it generates to test if the function exists).

This is not possible with CHECK_FUNCTION_EXISTS. Instead CHECK_LIBRARY_EXISTS must be used:

include(CheckLibraryExists)
CHECK_LIBRARY_EXISTS(rt clock_gettime "time.h" HAVE_CLOCK_GETTIME)

This will now work and output:

-- Looking for clock_gettime in rt - found

Update: In newer glibc 2.17+ clock_gettime has been moved from librt to libc.

So to be sure to find clock_gettime on all systems you would need to do two checks:

include(CheckLibraryExists)
CHECK_LIBRARY_EXISTS(rt clock_gettime "time.h" HAVE_CLOCK_GETTIME)

if (NOT HAVE_CLOCK_GETTIME)
   set(CMAKE_EXTRA_INCLUDE_FILES time.h)
   CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)
   SET(CMAKE_EXTRA_INCLUDE_FILES)
endif()
查看更多
我命由我不由天
3楼-- · 2019-04-26 15:51

This is what I am using:

include(CheckFunctionExists)
include(CheckLibraryExists)
check_library_exists(rt clock_gettime "time.h" HAVE_CLOCK_GETTIME)
if (HAVE_CLOCK_GETTIME)
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lrt")
    set(CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lrt")
else()
    # might also be in libc
    check_library_exists(c clock_gettime "" HAVE_CLOCK_GETTIME)
endif()
查看更多
登录 后发表回答