0

Just starting to learn C, and I found this example program on a C tutorial website, and it is giving an error upon compiling.

Here is the program, calculates the square root of a number based on user input:

#include <stdio.h>
#include <math.h>

int main()
{
    double num, root;

    /* Input a number from user */
    printf("Enter any number to find square root: ");
    scanf("%lf", &num);

    /* Calculate square root of num */
    root = sqrt(num);

    /* Print the resultant value */
    printf("Square root of %.2lf = %.2lf", num, root);

    return 0;
}

I compile it using gcc in Ubuntu:

gcc -o square_root square_root.c

And here is the error:

/tmp/cc9Z3NCn.o: In function `main':
square_root.c:(.text+0x4e): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

What am I doing wrong? I can see that the math module is imported, so why the error?

Again, I just started studying C today, and I just want to figure out how to get programs to run. Thank you for your patience as it must be something obvious.

MadHatter
  • 366
  • 1
  • 7
  • 23
  • 1
    Program is working fine. I think there is some issue with compiler. You can try compile your program on online IDE like ideone. It will work. – Anshu Kumar Sep 30 '18 at 01:46

2 Answers2

2

sqrt lives in the math library, so you need to tell your program to link to it with -lm:

gcc -o square_root square_root.c -lm
Travis Gockel
  • 26,877
  • 14
  • 89
  • 116
  • Can you offer any further explanation as to what exactly the `-lm` flag is doing? As in, does the `l` stand for link and the `m` stand for math? Why the need to tell it to link to the math library when it is imported at the top of the program? – MadHatter Sep 30 '18 at 01:54
  • 1
    C does not really have the concept of "importing" in the sense you're thinking. What the `#include` is doing is finding the headers for math (your program needs to know that a function called `sqrt` exists), while linking is used to find the implementation of `sqrt` (see https://stackoverflow.com/questions/924485/whats-the-difference-between-a-header-file-and-a-library). And yes, `-l` stands for "link" while the math library is `libm.so`; the `lib` prefix and `.so` suffix are left out, so you end with just `-lm`. – Travis Gockel Sep 30 '18 at 18:31
2

You need to compile it with -lm flag

gcc -o square_root square_root.c -lm
Raf.M
  • 43
  • 11