c - 未定义对 `pow' 和 `floor' 的引用

标签 c gcc undefined-reference

我试图用 C 语言制作一个简单的斐波那契计算器,但是在编译 gcc 时告诉我缺少 pow 和 floor 函数。怎么了?

代码:

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

int fibo(int n);

int main() {
        printf("Fib(4) = %d", fibo(4));
        return 0;
}

int fibo(int n) {
        double phi = 1.61803399;

        return (int)(floor((float)(pow(phi, n) / sqrt(5)) + .5f));
}

输出:

gab@testvm:~/work/c/fibo$ gcc fib.c -o fibo
/tmp/ccNSjm4q.o: In function `fibo':
fib.c:(.text+0x4a): undefined reference to `pow'
fib.c:(.text+0x68): undefined reference to `floor'
collect2: ld returned 1 exit status

最佳答案

您需要使用链接标志 -lm 进行编译,如下所示:

gcc fib.c -lm -o fibo

这将告诉 gcc 将您的代码链接到数学库。请务必将标记放在您要链接的对象之后

关于c - 未定义对 `pow' 和 `floor' 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675697/

相关文章:

c++ - 完美包装一个函数

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

c - 生成显示可执行文件中各个组件的内存范围的映射文件

c++ - 使用 makefile 编译 C++ 项目的问题

c - 通过字符串引用传递

将 C 编译成 MIPS

c++ - vector 的 undefined reference

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

C 编程打开和读取文件

没有循环的 C 程序意外地表现得像一个循环