- gcc sqrt function

Michael Meissner meissner@cygnus.com
Thu Oct 21 08:57:00 GMT 1999


On Thu, Oct 21, 1999 at 03:49:24PM +0100, Ted wrote:
> Dear Sirs,
> I am sorry to trouble you with this query, since my problems may be due
> to ignorance on my part.
> 
> I am starting to learn how to program in C, and I am having problems
> using the `sqrt' function.
> I am using a PII PC running Redhat 6.0 Linux.
> The version of gcc is:-  egcs-2.91.66  19990314/Linux
> The math.h header file is present in the `/usr/include' directory.
> The following file is taken from `Teach Yourself C' by Schildt, page
> 27:-
> 
> /************************************************************/
> #include <stdio.h>
> #include <math.h>
> 
> int main(void)
> {
>     double answer;
> 
>     answer = sqrt(10.0);
>     printf("%f", answer);
> 
>     return 0;
> }
> /************************************************************/
> 
> When I try to compile this with the command:-
> 
> `gcc -g -Wall -osqrt sqrt.c'

You need to include the math library with the -lm command (and the -lm has to
occur after the *.c files, since the linker searches things linearly, ie if it
scans the library first, it won't pull in sqrt since there are no references to
it yet, and when it gets to sqrt, it won't go back and search the library since
it already scanned it).  Use this command line:

	gcc -g -Wall -O -o sqrt sqrt.c -lm

> I get the error message:-
> 
> `8: undefined reference to `sqrt.'
> `collect2: ld returned 1 exit status'
> 
> Is there a bug in gcc, or am I not using the function correctly?  I have
> searched through the gcc info file, but I can't seem to find a solution.

This has been the way UNIX compilers have worked ever since the V7 days when
the stdio and math libraries appear (actually I don't recall if V6 had a math
library or not).

-- 
Michael Meissner, Cygnus Solutions
PMB 198, 174 Littleton Road #3, Westford, Massachusetts 01886
email: meissner@cygnus.com	phone: 978-486-9304	fax: 978-692-4482


More information about the Gcc-bugs mailing list