开始学习
< 返回

CMake 情景速查

如何使用 CMake 链接数学库

示例程序 GitHub 的 main.c 调用了 C 数学库的 sqrt 函数,如下:

#include <stdio.h>
#include <math.h>

int main() {
    int a = 100;
    printf("The sqrt of %d ==> %.2f\n", a, sqrt(a));
    return 0;
}

使用如下 CMakeLists.txt 进行构建:

cmake_minimum_required(VERSION 3.0)

project(LINK_MATH VERSION 0.0.1)

add_executable(go_sqrt main.c)

会出现如下错误:

main.c:(.text+0x19): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

原因是没有链接到 C 数学库。与自动链接的 libc 不同,libm 是一个单独的库,通常是 requires explicit linkage,因此需要链接到 libm。如果用 gcc 编译,添加 -lm 选项即可。而在 CMake 工程中,则需要在 CMakeLists.txt 中添加下面一行:

target_link_libraries(go_sqrt PRIVATE m)

第一个参数必须是目标,请根据您的情况进行修改。另外,target_link_libraries 必须放在 add_executable 之后。

Was this article helpful?
0 out of 5 stars
5 Stars 0%
4 Stars 0%
3 Stars 0%
2 Stars 0%
1 Stars 0%
Please Share Your Feedback
How Can We Improve This Article?
文章目录