TorosFanny
TorosFanny

Reputation: 1732

It's really strange that sometimes gcc can't find reference of sqrt but sometimes gcc can

I tried this code

/*main.c*/
#include <stdio.h>      /* printf */
#include <math.h>       /* sqrt */

int frequency_of_primes (int n) {
  int i, j;
  int freq = n - 1;
  for (i = 2; i <= n; ++i)
  for (j = sqrt(i); j > 1; --j)
    if (i%j==0) {--freq; break;}
  return freq;
}

int main() {
  printf("%f\n", sqrt(4.0));
  return 0;
}

and compiled it with gcc main.c, it reported that undefined reference tosqrt'. I already know add-lm` option can resolve this issue. But what really surprises me is this:

#include <stdio.h>      /* printf */
#include <math.h>       /* sqrt */

// int frequency_of_primes (int n) {
//   int i, j;
//   int freq = n - 1;
//   for (i = 2; i <= n; ++i)
//   for (j = sqrt(i); j > 1; --j)
//     if (i%j==0) {--freq; break;}
//   return freq;
// }

int main() {
  printf("%f\n", sqrt(4.0));
  return 0;
}

The main function also calls sqrt, but ld doesn't report any errors.

Upvotes: 4

Views: 94

Answers (1)

unwind
unwind

Reputation: 399863

That's because the optimizer is handling the constant case you're using.

It's the sqrt(i) call inside frequency_of_primes() that's the problem, the call in main() is optimized out. You can figure that out by reading the generated code for the latter case, it'll just load a constant 2.0 and be done with it.

Upvotes: 7

Related Questions