Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have the code below:

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

int main(int argc, char **argv){

float index;
	for(index = 0; index <= 360; index++){
		index = (3.14/180) * index; //convert to radiant
		float a = cos(index);
		printf("a = %f\n", a);
	}
}


And when I tried to compile, I got the error below:

/tmp/ccEPoXwg.o: In function `main':
test.c:(.text+0x6b): undefined reference to `cos'
collect2: ld returned 1 exit status

What is weird is that when I try this (without the for loop) :
C++
float a = cos(3.14);
  printf("a = %f\n", a);


I get no errors

Can anyone, please help me.

Thank you in advance
Posted
Updated 19-Dec-10 4:52am
v2

The problem is that you have only a cos(double) function in your math library but you are trying to call a cos(float) function in the loop. Without the loop you pass a double type number to cos() (because you say cos(3.14) and not cos(3.14f)). But in the loop you pass in a float (float index). Declare index as a double or cast index to a double when you call cos()!

Most math libraries contain a cos(double) and a cosf(float) function. You can try using cosf() if you want to stick with your float data!
 
Share this answer
 
v3
Comments
Richard MacCutchan 19-Dec-10 15:54pm    
Excellent answer, I certainly missed that subtle difference.
The_Real_Chubaka 20-Dec-10 4:57am    
Thank you for you answer. The main mistake i made is that i forgot to link with the math library. I also did not know that there was no cos(float) function in the math library. Thank you for that information too.
You must link with the math library, namely:
gcc myprogram.c -lm

:)
 
Share this answer
 
Comments
The_Real_Chubaka 20-Dec-10 4:59am    
Thank you. I did what you suggested.
My code works now.
Lightning Monster 18-Dec-22 15:11pm    
WTF My library is not working and I am finding a solution for this error for a week its solution is only type -lm when compiling!! BTW Thank U sir/madam!!
Check your build statement, or make script, to ensure that you are including the correct math library in your link phase.

pasztorpisti has the correct answer; well done considering the sample does not use Hungarian notation. :laugh:
 
Share this answer
 
v2
Comments
The_Real_Chubaka 20-Dec-10 4:58am    
Thank you for you answer. The code work now.
I just forgot to link with the math library.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900