Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

gcc

ld

math.sqrt

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.

like image 580
TorosFanny Avatar asked Mar 15 '23 09:03

TorosFanny


1 Answers

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.

like image 170
unwind Avatar answered Mar 16 '23 22:03

unwind