【问题标题】:Code is not linked with math.h even though -lm is in add_compile_options [duplicate]即使 -lm 在 add_compile_options [重复] 中,代码也没有与 math.h 链接
【发布时间】:2021-10-15 09:26:20
【问题描述】:

我有一些借助 CMake(在 CLion 中)编译的 C 代码:

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

typedef struct ball {
    double x, y, z, r;
} ball;

bool intersect(ball *a, ball *b) {
    double d = sqrt(pow(a->x - b->x, 2) + pow(a->y - b->y, 2) + pow(a->z - b->z, 2));
    return d <= a->r + b->r;
}

我还有我的 CMakeLists,它指定 -lm 作为编译器选项。也是最后一个选项:

cmake_minimum_required(VERSION 3.20)
project(untitled C)

set(CMAKE_C_STANDARD 99)

add_compile_options(-Wall -Werror -Wformat-security -Wignored-qualifiers -Winit-self -Wswitch-default -Wfloat-equal -Wpointer-arith -Wtype-limits -Wempty-body -Wno-logical-op -Wstrict-prototypes -Wold-style-declaration -Wold-style-definition -Wmissing-parameter-type -Wmissing-field-initializers -Wnested-externs -Wno-pointer-sign -Wno-unused-result -std=gnu99 -lm)

add_executable(untitled main.c)

但是,在编译时,我得到了一堆未定义的引用:

Scanning dependencies of target untitled
[ 50%] Building C object CMakeFiles/untitled.dir/main.c.o
[100%] Linking C executable untitled
/usr/bin/ld: CMakeFiles/untitled.dir/main.c.o: in function `intersect':
/home/keddad/CLionProjects/untitled/main.c:10: undefined reference to `pow'
/usr/bin/ld: /home/keddad/CLionProjects/untitled/main.c:10: undefined reference to `pow'
/usr/bin/ld: /home/keddad/CLionProjects/untitled/main.c:10: undefined reference to `pow'
/usr/bin/ld: /home/keddad/CLionProjects/untitled/main.c:10: undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
gmake[3]: *** [CMakeFiles/untitled.dir/build.make:93: untitled] Error 1
gmake[2]: *** [CMakeFiles/Makefile2:83: CMakeFiles/untitled.dir/all] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:90: CMakeFiles/untitled.dir/rule] Error 2
gmake: *** [Makefile:124: untitled] Error 2

我做错了什么?我已经阅读了有关该主题的另一个问题,我认为只要我有-lm,并且它被指定为最后一个编译器参数,它应该可以正常工作。不过,这里好像不是这样。

【问题讨论】:

    标签: c cmake


    【解决方案1】:

    add_compile_options 是添加编译器 标志,而不是链接器标志或库。

    要与库链接,请使用target_link_libraries 命令:

    add_executable(untitled main.c)
    target_link_libraries(untitled m)
    

    另外,请选择target_compile_options 而不是add_compile_options

    【讨论】:

    • 谢谢!我认为它只是将所有这些论点按原样传递给 GCC
    • @keddad 构建分两步完成:编译成目标文件,以及将目标文件与库链接。
    猜你喜欢
    • 2011-12-06
    • 2013-04-27
    • 1970-01-01
    • 2020-04-17
    • 2021-06-07
    • 2019-05-02
    • 2021-12-26
    • 2012-01-06
    相关资源
    最近更新 更多