c - 对 `sin' 的 undefined reference ,即使我使用 <math.h> 和 -lm

标签 c linker-errors undefined-reference

我注意到当我使用 sin 时编译器无法识别函数内部,这是一个示例:

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

float sinus(float a){
    return sin(a);}

int main(int argc, char **argv)
{
    double a = sinus(2);
    printf("%f \n", sin(2));
    printf("%f", a);
    return 0;
}

如果我直接在 main 中使用它,它工作正常,但在用户定义的函数中,它会给我这个错误 undefined reference to sin .

为了编译,我使用 gcc -Wall -lm -lc -lgcc -o "%e" "%f" .

最佳答案

对库的引用通常位于命令行末尾,特别是在指定源之后:

gcc -Wall -o "%e" "%f" -lm 

(指定 C 库不是必需的,它是隐式链接的)

来自documentation :

-l library

[...]

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded.

关于c - 对 `sin' 的 undefined reference ,即使我使用 <math.h> 和 -lm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59573439/

相关文章:

c++ - Directshow C++ CLR 中未解析的 token (0A00001x)

c++ - 为什么编程语言被编译为汇编语言而不是二进制语言?

visual-c++ - 如何声明一个对象并从同一解决方案中不同项目中定义的类调用其方法?

c - OCaml:链接 C 和 OCaml 的问题

c++ - undefined reference

c - 对 `function' 的 undefined reference

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c - gcc 堆栈优化?

c++ - GLTessellator 崩溃

c - 访问存储在 mxArray 中的对象的字符串属性