13

CMake 似乎在 GCC 编译命令的前面添加了链接器标志,而不是在末尾附加它。如何使 CMake 附加链接器标志?

这是一个重现问题的简单示例。考虑使用以下 C++ 代码clock_gettime

// main.cpp
#include <iostream>
#include <time.h>

int main()
{
    timespec t;
    clock_gettime(CLOCK_REALTIME, &t);
    std::cout << t.tv_sec << std::endl;
    return 0;
}

这是一个 CMakeLists.txt,用于编译上面的 C++ 文件:

cmake_minimum_required(VERSION 2.8)
set(CMAKE_EXE_LINKER_FLAGS "-lrt")
add_executable(helloapp main.cpp)

请注意,我们已添加-lrt,因为它具有clock_gettime.

编译使用:

$ ls
  CMakeLists.txt main.cpp
$ mkdir build
$ cd build
$ cmake ..
$ make VERBOSE=1

这会引发此错误,即使您可以-lrt在命令中看到:

/usr/bin/c++ -lrt CMakeFiles/helloapp.dir/main.cpp.o -o helloapp -rdynamic 
CMakeFiles/helloapp.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x15): undefined reference to `clock_gettime'
collect2: ld returned 1 exit status
make[2]: *** [helloapp] Error 1

这里的问题是 CMake 生成的 C++ 编译命令已经-lrt前置。编译工作正常,如果它是:

/usr/bin/c++ CMakeFiles/helloapp.dir/main.cpp.o -o helloapp -rdynamic -lrt

如何使 CMake 在末尾附加链接器标志?

4

1 回答 1

13

一般来说你不能(我认为),但在你想要链接到特定库的特定情况下,你应该使用语法

target_link_libraries(helloapp rt)

反而。CMake 知道这对应于传递-lrt链接器命令行。

于 2014-03-11T07:44:22.793 回答