Need to use -lm in Clang with pow(), but not sqrt(

2019-06-24 00:24发布

问题:

On FreeBSD 10.1 and using Clang version 3.4.1

Now I have seen other threads asking how to compile with using pow(), but I haven't seen a thread with this question. Take for example:

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

int main()
{
  float result;
  result = pow(2,3);
  printf("%d", result);
  return 0;
}

Now using pow(), I need to issue clang the argument -lm.

cc -lm -o name name.c

However, replacing pow(2,3) with sqrt(5);, I can compile with cc -o name name.c. If they both use math.h, then why does pow() need to be linked to the library? Side not: Installed gcc to test, and I don't need to use -lm at all.

回答1:

You are targeting a processor whose floating point hardware implements sqrt directly, as do all IEEE-754 compliant units. As such, the compiler can generate code for sqrt directly and does not need to link to a library function.

On the other hand, floating point hardware does not typically offer implementations of pow and so it does need to be implemented in a library.



标签: c clang