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
a . You need to link your program with this library so that the calls to functions like pow() are resolved. This solved my issue.
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.
Link your program with the `libm. a' library, e.g. by specifying `-lm' on the link command line.
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.
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.
Add -lm to your link options, since pow() and floor() are part of the math library:
gcc fib.c -o fibo -lm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With