Auburn Auburn - 1 year ago 111
C Question

Error when using sqrt in C

I am having trouble using the sqrt function in C even though I am using the math.h header and I am using doubles. When trying to run the following code:

#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
int J = 1000000;

int sieve(int J)
int P[J+1]; P[0] = 0; P[1] = 0; int i;

for (i = 2; i <= J; i++) //set all values of P to 1 initially
{ P[i] = 1;}

int p = 2;

double y = (double) J;
double J2 = sqrt(y);

I receieve the error:

/tmp/ccAhS08O.o: In function 'sieve':
test.c:(.text+0xf8): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

Answer Source

With all recent versions of GCC, you have to explicitly link to the math library when compiling, since it is not automatically linked to along with the rest of the standard C library).

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.

For example: gcc -o foo foo.c -lm

Or you could add the flag in the Makefile, you are using to compile

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download