Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

c - Gcc uses sqrt without including math.h

Anyone knows why this c program compiles and uses the sqrt of math.h?

this would output 2.236068

main.c

#include <stdio.h>
#include "math_utils.h"

int main(void){
  printf("%f
", sqrt(5));
  return 0;
}

math_utils.h

#ifndef MATH_UTILS_Hs
#define MATH_UTILS_Hs

double sqrt(double number){
  return number + 5;
}

#endif // MATH_UTILS_Hs

I am currently using mingw GCC on windows

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

gcc performs an optimization where it expects standard library functions to behave like the standard says to turn calls into the C standard library into more efficient machine code. For example, it's likely that gcc emits a single fsqrt instruction for your sqrt() call, never calling your custom sqrt() at all.

You can turn off this behaviour by supplying -fno-builtin to turn this optimization off for all recognized functions or by supplying -fno-builtin-function to turn off this optimization for function only. For example, -fno-builtin-sqrt would make gcc honour your non-standard sqrt().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...