Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

math.h - Using pow() function throws undefined reference error in C

Why does the following bit of code work in C:

int res = pow(2, 3);
printf("%d
", res);

while this other doesn't?

int a = 2;
int b = 3;

int res = pow(a, b);
printf("%d
", res);

Even if I try

double a = 2;
double b = 3;

double res = pow(a, b);
printf("%f
", res);

I get an

undefined reference to `pow'

What am I doing wrong?

question from:https://stackoverflow.com/questions/4174080/using-pow-function-throws-undefined-reference-error-in-c

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

1 Reply

0 votes
by (71.8m points)

When it works, it's because the calculation was done by the compiler itself (and included in the binary as if you wrote it out)

printf("8
");

When it doesn't work, is because the pow function is included in the math library and the math library isn't linked with your binary by default.
To get the math library to be linked, if your compiler is gcc, use

gcc ... -lm ...

With other compilers, should be the same :)
but read the documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...