为什么常数的平方根在编译时已知不需要连接数学库? [英] Why do square roots of constants known at compile time not require linking the math library?

查看:185
本文介绍了为什么常数的平方根在编译时已知不需要连接数学库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简称 C 程序:

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


#define K 20
// int K = 20;

int main() {
    printf("%f\n", sqrt(K));
}

这个程序,给出,编译与的gcc foo.c的,并产生正确的输出。

This program, as given, compiles with gcc Foo.c, and produces correct output.

但是,如果我们注释掉的#define 行,并在 INT K = 20 行注释,那么我们得到的未定义参考开方编译时错误,这只能通过的gcc foo.c的-lm

However, if we comment out the #define line, and comment in the int K = 20 line, then we get a compile-time error of undefined reference to sqrt', which can only be fixed by compiling with gcc Foo.c -lm.

我在 GCC 4.7.3 的Ubuntu 13.04

推荐答案

在编译过程中,编译器确定要调用一个常量文字作为唯一参数的函数。因此,它可以通过用函数调用的结果优化

During compilation, the compiler determines that you are calling a function with a constant literal as the only argument. So it can optimise by substituting the result of the function call.

它计算在编译时平方根。请注意,这不,在您的评论建议,注资code在运行时计算。

It calculates the sqrt at compile time. Note that it does not, a suggested in your comment, inject code to calculate it at run time.

当然,编译器也只对某些功能做到这一点。

Of course the compiler well only do this for certain functions.

这个优化后,有没有要求在运行时调用开方,所以如果你没有挂靠你没有得到一个错误。

After this optimisation there is no requirement to call sqrt at run time, so you don't get an error if you didn't link it.

这篇关于为什么常数的平方根在编译时已知不需要连接数学库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆