From mboxrd@z Thu Jan 1 00:00:00 1970 From: fubar@example.com (Ffoobarr) To: help-gcc@gnu.org Subject: Re: math.h prob Date: Tue, 30 Nov 1999 23:28:00 -0000 Message-ID: References: <38204719.FD2DC371@clinmed.gla.ac.uk> X-SW-Source: 1999-11n/msg00014.html Message-ID: <19991130232800.ug2LI5J08hjAskiFzltnQ-G6wJMsbn717lAz3saYmpI@z> 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 >#include >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!