Quick C programming question!

TecHNooB

Diamond Member
Sep 10, 2005
7,458
1
76
How do you use the pow function with a variable? I made a program that will convert binary values into decimal values and used something like pow(10, n). But when I transfer the program onto a school computer, the compiler won't accept it. I get this error:

Undefined first referenced
symbol in file
pow /var/tmp//ccU8hSXp.o
ld: fatal: Symbol referencing errors. No output written to a.out

I have included math.h and pow(10, n) works on my laptop. What's wrong??
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
You probably just need to add -lm to your compile command for the linker to be able to find the math libraries.
 

TecHNooB

Diamond Member
Sep 10, 2005
7,458
1
76
I have #include <stdio.h> and #include <math.h> on the top. If I just plug in numbers like pow(2, 3), I get 8. If I do pow(2, n), I get the error message :(
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
Ok, the error you posted in the OP looks like a linker error though. What is n defined as? Can you post the code?
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
Originally posted by: Nothinman
Ok, the error you posted in the OP looks like a linker error though. What is n defined as? Can you post the code?
It is possible the compiler saw pow(2,3) in the code and realised it could calculate that at compile time instead of inserting a runtime call to the function. With pow(2,n) it has to use the runtime call since it can't be calculated at compiled time.

The reason it works on Windows is because the math library is built into the C library under Windows. On most platforms, this is not the case, and you have to add -lm to your compile line to get it to link in. If you did 'cc foo.c' before, use 'cc foo.c -lm' and it will link in the math library.
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
It is possible the compiler saw pow(2,3) in the code and realised it could calculate that at compile time instead of inserting a runtime call to the function. With pow(2,n) it has to use the runtime call since it can't be calculated at compiled time.

That is a good possibility, I hadn't thought of that.