C's pow() doesn't work with a variable exponent

时光怂恿深爱的人放手 提交于 2019-12-24 00:04:46

问题


I have a small bit of code:

#include <math.h>

int main(void){
    pow(2.0,7.0);
    //Works

    double x = 3.0;
    pow(2.0,x);
    //Fails with error "undefined reference to 'pow'"
    return 0;
}

I have linked -lm in my Eclipse compiler settings: gcc -O0 -g3 -Wall -lm -c -fmessage-length=0 -MMD -MP -MF"src/pgm.d" -MT"src/pgm.d" -o "src/pgm.o" "../src/pgm.c", so I'm not sure what the source of the error is. What am I not doing corectly?


回答1:


Put -lm to the end of the command line.




回答2:


Your -lm option doesn't work, because it needs to follow the input sources on the command line:

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

The first pow(2.0,7.0) works because it's evaluated by the compiler as a constant expression, and doesn't need pow at runtime.




回答3:


You need to link to the math library with the -lm flag for the compiler.

The first example work because the compiler can inline the value(in fact, 2^7 will always be equal to 128), but when using variable parameter to pow(), it can't inline its value, since its value will only be know at runtime, thus you need to explicetely link the standard math library, where instead of inlining the value, it will call the function.



来源:https://stackoverflow.com/questions/16802263/cs-pow-doesnt-work-with-a-variable-exponent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!