0

When I compile this code:

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

int main() {

    char str[] = "3.6";

    double res = atof(str);

    printf("%f\n", sqrt(res));

    return 0;
}

I get this error:

    ====================[ Build | untitled12 | Debug ]==============================
/snap/clion/81/bin/cmake/linux/bin/cmake --build /home/abdo/CLionProjects/untitled12/cmake-build-debug --target untitled12 -- -j 4
[ 50%] Linking C executable untitled12
/usr/bin/ld: CMakeFiles/untitled12.dir/main.c.o: in function `main':
/home/abdo/CLionProjects/untitled12/main.c:11: undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/untitled12.dir/build.make:84: untitled12] Error 1
make[2]: *** [CMakeFiles/Makefile2:73: CMakeFiles/untitled12.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:85: CMakeFiles/untitled12.dir/rule] Error 2
make: *** [Makefile:118: untitled12] Error 2

I get same error when I replace 'sqrt' with 'log' or 'ln' ...

compiler: cc (Ubuntu 8.3.0-6ubuntu1) 8.3.0

Community
  • 1
  • 1
Abdo21
  • 498
  • 4
  • 14

1 Answers1

1

The math library must be linked in when compiling. Add the -lm flag to your gcc command, after the source or object file(s).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
BTables
  • 4,413
  • 2
  • 11
  • 30