How to use sqrt() function with gcc?

J

John

I'm trying to use the sqrt() function in Linux with GCC v3.3.6,
compiling with this command:
$ gcc sourcefile.c

I get this error:
In function 'main': undefined reference to 'sqrt'
collect2: ld returned 1 exit status

Here is my source code:
#include <stdio.h>
#include <math.h>
main()
{
double num, sq_double;
scanf("%d", &num);
sq_double = sqrt(num);
}

What am I doing wrong? Is there something special I need to do to use
the math.h functions?
 
R

Richard Heathfield

John said:
I get this error:
In function 'main': undefined reference to 'sqrt'
collect2: ld returned 1 exit status

scanf("%d", &num);

%lf for double. %d is for ints.
sq_double = sqrt(num);
}

What am I doing wrong? Is there something special I need to do to use
the math.h functions?

For gcc, yes, you need to tell it to link the math library in, by adding -lm
at the end of your gcc call.
 
K

Keith Thompson

John said:
I'm trying to use the sqrt() function in Linux with GCC v3.3.6,
compiling with this command:
$ gcc sourcefile.c

I get this error:
In function 'main': undefined reference to 'sqrt'
collect2: ld returned 1 exit status
[...]

<http://www.c-faq.com/>, question 14.3.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top