0

I am trying to write a code which displays the roots of a given quadratic equation and for that i need the 'math.h' header file so I can use the 'sqrt()' function, but whenever I try to run the code it seems to not include the 'math.h' header file. I am using atom to write my code and I have installed an extension to compile and run the code automatically when I press F5. How do I make GCC include the header files automatically so that when I press F5 the code doesnt return any errors? here is my code:

#include <stdio.h>
#include <math.h>
int main(){
  int a, b ,c; 
  double d;
  float root1, root2;
  printf("Enter values of a, b and c considering the equation ax^2+bx+c=0\n");
  scanf("%d %d %d",&a,&b,&c);
  d=(b*b)-(4*a*c);
  if (d==0){
    printf("\nThe given quadratic equation has real and equal roots");
    root1=(-b)/(2*a);
    root2=root1;
    printf("\nThe roots are %f and %f",root1,root2);
  }
  else if (d>0){
    printf("\nThe given quadratic equation has real and unequal roots");
    root1=((-b)+sqrt(d))/(2*a);
    root2=(b+sqrt(d))/(2*a);
    printf("\nThe roots are %f and %f",root1,root2);
  }
  else{
    printf("\nThe given quadratic equation has imaginary roots");
  }
  return 0;
}

and when compiling I get the following error:

/usr/bin/ld: /tmp/ccNMDO04.o: in function main': roots.c:(.text+0x10b): undefined reference to sqrt' /usr/bin/ld: roots.c:(.text+0x140): undefined reference to `sqrt' collect2: error: ld returned 1 exit status

  • 1
    It's finding `math.h` just fine. You need `-lm` as the last arg to your `cc` command to link to the library that has the `sqrt` function. – Craig Estey May 28 '21 at 03:05
  • I think https://stackoverflow.com/questions/5248919/undefined-reference-to-sqrt-or-other-mathematical-functions is the canonical duplicate. – Nate Eldredge May 28 '21 at 03:08
  • okay i started experimenting in the settings of the atom extension and a just added the `-lm` to the extra command line argumetns and it works fine now – Shreyas Gavhalkar May 28 '21 at 03:38

0 Answers0