Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to `pow' and `floor'

I'm trying to make a simple fibonacci calculator in C but when compiling gcc tells me that I'm missing the pow and floor functions. What's wrong?

Code:

#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)); } 

Output:

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 
like image 634
Gabriele Cirulli Avatar asked Dec 29 '11 17:12

Gabriele Cirulli


People also ask

How do you fix an undefined reference to POW?

a . You need to link your program with this library so that the calls to functions like pow() are resolved. This solved my issue.

What is undefined reference to POW in C?

When we use the pow function or any other math functions from math header in c program on linux environment (RHEL, Fedora or CentOS), need to use -lm option for compilation. otherwise you will get undefined reference to pow error, when you compile below program with no -lm option.

How do I link a program to LIBM?

Link your program with the `libm. a' library, e.g. by specifying `-lm' on the link command line.

How do you use math h in GCC?

If you are compiling on the command-line with the gcc or g++ command, you would accomplish this by putting -lm at the end of the command. If you are going to compile a C program with math. h library in LINUX using GCC or G++ you will have to use –lm option after the compile command.


2 Answers

You need to compile with the link flag -lm, like this:

gcc fib.c -lm -o fibo 

This will tell gcc to link your code against the math lib. Just be sure to put the flag after the objects you want to link.

like image 61
Fred Avatar answered Sep 27 '22 19:09

Fred


Add -lm to your link options, since pow() and floor() are part of the math library:

gcc fib.c -o fibo -lm 
like image 35
Yann Droneaud Avatar answered Sep 27 '22 20:09

Yann Droneaud