468,513 Members | 1,866 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

How to use sqrt() function with gcc?

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?
Aug 4 '06 #1
3 41068
Try
gcc -lm sourcefile.c

John wrote:
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?
Aug 4 '06 #2
John said:
I get this error:
In function 'main': undefined reference to 'sqrt'
collect2: ld returned 1 exit status
<snip>
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.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Aug 4 '06 #3
John <us**@home.netwrites:
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.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 4 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Prune Tracy | last post: by
10 posts views Thread by pauldepstein | last post: by
45 posts views Thread by JaSeong Ju | last post: by
7 posts views Thread by rahul8143 | last post: by
13 posts views Thread by Michael McNeil Forbes | last post: by
13 posts views Thread by siggi | last post: by
73 posts views Thread by Steph Barklay | last post: by
6 posts views Thread by Blue sky | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.