Click here to Skip to main content
13,193,970 members (47,512 online)
Rate this:
Please Sign up or sign in to vote.
See more:

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.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) :
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
Updated 19-Dec-10 4:52am
Henry Minute225.8K
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!
Richard MacCutchan 19-Dec-10 15:54pm
Excellent answer, I certainly missed that subtle difference.
hervebags 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.
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

hervebags 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:
hervebags 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
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.171018.2 | Last Updated 19 Dec 2010
Copyright © CodeProject, 1999-2017
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