简体   繁体   English

错误在gcc中使用数学函数?

[英]error In using math function in gcc?

When I am passing constant value in log2() as follow 当我在log2()中传递常量值时,如下所示

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

int main(int argc, char* argv[]) 
{
int var;
var= log2(16);
printf("%d",var);
return 0;
}

gcc prog.c (NO Error) 4 gcc prog.c(NO Error)4

But when I am passing variable in function log2(var) gives error undefined reference to `log2' I require to link library ie -lm 但是当我在函数log2(var)中传递变量时,给出了对`log2'的错误未定义引用我需要链接库即-lm

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

int main(int argc, char* argv[]) 
{ 
int var,i;
i= log2(var);
printf("%d",i);
return 0;
}

Gives error 给出错误

undefined reference to `log2'

In the first piece of code, the compiler replaces log2(16) with the constant 4 . 在第一段代码中,编译器用常量4替换log2(16) The compiler usually optimizes constant math this way. 编译器通常以这种方式优化常量数学。 That's the reason you don't see an error. 这就是你没有看到错误的原因。

See the generated code for confirmation. 请参阅生成的代码以进行确认。 This is for your first version: 这是您的第一个版本:

main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $32, %esp
    movl    $4, 28(%esp)
    movl    $.LC0, %eax
    movl    28(%esp), %edx
    movl    %edx, 4(%esp)
    movl    %eax, (%esp)
    call    printf
    movl    $0, %eax
    leave
    ret

There is no call to log2. 没有调用log2。 The compiler already replaced it by the constant 4 ( movl $4, 28(%esp) ). 编译器已将其替换为常量4( movl $4, 28(%esp) )。

This one is for your second version: 这个是你的第二个版本:

main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $48, %esp
    fildl   40(%esp)
    fstpl   (%esp)
    call    log2
    fnstcw  30(%esp)
    movzwl  30(%esp), %eax
    movb    $12, %ah
    movw    %ax, 28(%esp)
    fldcw   28(%esp)
    fistpl  44(%esp)
    fldcw   30(%esp)
    movl    $.LC0, %eax
    movl    44(%esp), %edx
    movl    %edx, 4(%esp)
    movl    %eax, (%esp)
    call    printf
    movl    $0, %eax
    leave
    ret

As you can see there is a call log2 in this version. 正如您所看到的,此版本中有一个call log2 Thats why -lm is needed for the second version. 这就是为什么第二个版本需要-lm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM