Gcc 如何使CMake附加链接器标志而不是预先添加它们?
CMake似乎在GCC编译命令的前面添加链接器标志,而不是在末尾添加链接器标志。如何使CMake附加链接器标志 下面是一个简单的例子来重现这个问题。 考虑C++代码使用<代码> CcLogyGETTime<代码>:< /P>Gcc 如何使CMake附加链接器标志而不是预先添加它们?,gcc,linker,cmake,linker-flags,Gcc,Linker,Cmake,Linker Flags,CMake似乎在GCC编译命令的前面添加链接器标志,而不是在末尾添加链接器标志。如何使CMake附加链接器标志 下面是一个简单的例子来重现这个问题。 考虑C++代码使用 CcLogyGETTime:< /P> // main.cpp #include <iostream> #include <time.h> int main() { timespec t; clock_gettime(CLOCK_REALTIME, &t); std::c
// 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;
}
请注意,我们添加了-lrt
,因为它具有clock\u 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在末尾附加链接器标志?通常不能(我认为),但在特定情况下,您需要针对特定库进行链接,应该使用语法
target_link_libraries(helloapp rt)
相反。CMake知道这对应于在链接器命令行上传递
-lrt
。target\u link\u libraries(helloapp rt)
根据Peter的评论编辑,并添加了一些解释。
target_link_libraries(helloapp rt)