Results 1 to 4 of 4

Thread: Getting math functions to work in C

  1. #1
    Join Date
    Jul 2013
    Beans
    9

    Getting math functions to work in C

    I am using GCC on Ubuntu 12.10. I am trying to use math functions; specifically sqrt(). When I use a line of code that has a constant in it "sqrt(4)" the function compiles and gives me the right answer in the terminal. When I use a variable "sqrt(number)" the compiler returns with "undefined reference to `sqrt'". I believe I need to use the linker to a math library since I encountered this same problem with Netbeans. I do not know and am not able to find the name of the library or file that would solve this problem. I have tried "-std=iso9899:1990" since that std requires only <math.h> and I still get the same error message. Here is the snippet of code from the program:
    double number;

    printf ("Enter a number: ");
    scanf("%lf", &number);
    printf ("The sqrt of 4 is: %lf\n", sqrt(4));
    printf ("The sqrt of your number is: %lf\n", sqrt(number));

  2. #2
    Join Date
    Apr 2012
    Beans
    6,760

    Re: Getting math functions to work in C

    The library is libm, it may be specified on the gcc command line as -lm e.g.

    Code:
    gcc -o yourprog yourprog.c -lm

  3. #3
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,264
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: Getting math functions to work in C

    Quote Originally Posted by seriouslylinux View Post
    I believe I need to use the linker to a math library since I encountered this same problem with Netbeans. I do not know and am not able to find the name of the library or file that would solve this problem.
    steeldriver has given the right answer, but I wonder, did you try "man sqrt"? In the synopsis, it says "Link with -lm."

  4. #4
    Join Date
    Jul 2013
    Beans
    9

    Re: Getting math functions to work in C

    Thank you for the info and the replies. The math functions are working.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •