Click here to Skip to main content
11,790,021 members (48,877 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C Linux

I have the code below:

 #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.cFrown | :( 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) :
float a = cos(3.14);
  printf("a = %f\n", a);

I get no errors

Can anyone, please help me.

Thank you in advance
Posted 19-Dec-10 4:32am
Edited 19-Dec-10 4:52am
Henry Minute224.7K
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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!
hervebags at 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.
Richard MacCutchan at 19-Dec-10 15:54pm
Excellent answer, I certainly missed that subtle difference.
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

You must link with the math library, namely:
gcc myprogram.c -lm
Smile | :)
hervebags at 20-Dec-10 4:59am
Thank you. I did what you suggested.
My code works now.
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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 | :laugh:
hervebags at 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)

  Print Answers RSS
0 OriginalGriff 1,029
1 Maciej Los 790
2 KrunalRohit 686
3 CPallini 606
4 Richard MacCutchan 460

Advertise | Privacy | Mobile
Web03 | 2.8.1509028.1 | Last Updated 19 Dec 2010
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100