This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: math.h prob


Dave Brennan wrote:
>I am fairly new to C programming, especially to using gcc, so I am sorry
>if my question is a bit simple!
>I am using gcc 2.8.1 on a Sun workstation (solaris 2.7).
>I am having problems using maths functions. e.g if I have the program
>
>#include <stdio.h>
>#include <math.h>
>main()
>{
>double x;
>scanf("%lf",&x);
>printf("x = %lf",sqrt(x));
>}
>
>and try to compile it using,
>gcc -o test mattest.c
>I get the following error:
>Undefined                       first referenced
> symbol                             in file
>sqrt                                /var/tmp/cc9Eay_r1.o
>ld: fatal: Symbol referencing errors. No output written to test

Hi Dave.  This is a very, very frequently asked question.  The problem
is the math library is separate from the regular C library and you need
to explicitly link in the math library, using the -lm flag.  So, in your
case, the correct compiler command would be:

gcc -o mattest mattest.c -lm

Also, please take note of the fact that I changed the name of the
executable to something other than test.  There is already a command
called 'test' that you will problably end up running instead of your
'test'.

And... I hope you don't mind a few style suggestions:  Explicitly declare
main's return type and parameters as 'int main(void)' instead of just
'main()', and add a 'return 0;' line before the closing brace.
In your printf() format string, you should use '%f' instead of '%lf'.
Your scanf() format specifier is fine, but you might want to consider
checking the return value of scanf() for failure in case the user didn't
type something that could be converted to a floating-point value (like
ABCDEFG instead of 3.14).

Hope this helps!


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]