4

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Webtm
  • 87
  • 5
  • See [log(10.0) can compile but log(0.0) cannot?](http://stackoverflow.com/q/24294578/1708801) basically it is using a builtin and so in those cases it does not need to link against the math library. – Shafik Yaghmour Aug 12 '15 at 20:34
  • @ShafikYaghmour I think that's a different issue. The compiler is evaluating `log(10.0)` rather than writing code to evaluate at runtime. – David Heffernan Aug 12 '15 at 20:44
  • @ShafikYaghmour I don't agree. – David Heffernan Aug 12 '15 at 20:54
  • @DavidHeffernan well the best way to test is to use -fno-builtin if that changes the need for -lm then it is indeed the case. – Shafik Yaghmour Aug 12 '15 at 20:58
  • Indeed using `-fno-builtin` forces `-lm` to be required [see it live](http://coliru.stacked-crooked.com/a/6b04f743ad98ac1e) so this is indeed the same issue as I linked above. In order to make the above program work we would have to add `-lm`. – Shafik Yaghmour Aug 12 '15 at 23:58

1 Answers1

6

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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490