为什么CHECK_FUNCTION_EXISTS在CMake中找不到clock_gettime?

Joa*_*kim 7 c cmake

怎么CHECK_FUNCTION_EXISTS没找到clock_gettime

我在我的代码中使用以下代码CMakeLists.txt:

include(CheckFunctionExists)

set(CMAKE_EXTRA_INCLUDE_FILES time.h)
CHECK_FUNCTION_EXISTS(clock_gettime HAVE_CLOCK_GETTIME)
Run Code Online (Sandbox Code Playgroud)

这是在我知道的POSIX系统上clock_gettime.但我只是得到:

-- Looking for clock_gettime - not found
Run Code Online (Sandbox Code Playgroud)

Joa*_*kim 9

由于clock_gettime被发现在librt我们需要做检查时,链接到(否则CMake的将只是无法编译生成测试是否存在功能测试程序).

这是不可能的CHECK_FUNCTION_EXISTS.而是必须使用CHECK_LIBRARY_EXISTS:

include(CheckLibraryExists)
CHECK_LIBRARY_EXISTS(rt clock_gettime "time.h" HAVE_CLOCK_GETTIME)
Run Code Online (Sandbox Code Playgroud)

这将现在工作和输出:

-- Looking for clock_gettime in rt - found
Run Code Online (Sandbox Code Playgroud)

更新:在新的glibc 2.17+ clock_gettime已从移动librtlibc.

因此,为了确保clock_gettime在所有系统上找到您需要进行两项检查:

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()
Run Code Online (Sandbox Code Playgroud)

  • 这将随glibc 2.17版本而改变.clock_*符号被移动到libc中,代码将不再需要链接到librt. (3认同)