pow 不接受第二个参数作为 gcc 上的变量

发布于 2024-09-02 06:38:44 字数 611 浏览 1 评论 0原文

pow 不接受第二个参数作为 gcc 上的变量

以下代码在 VC++10 上工作正常

// file test.cc
#include "stdafx.h"
#include <stdio.h>
#include <math.h>

int main(void)
{   
    double x = 10;
    int y = 20;
    printf("%f\n", pow(x, y));
    return 0;
}

但以下代码在 gcc 上不起作用:

// test.c
#include <stdio.h>
#include <math.h>

int main(void)
{   
    double x = 10;
    int y = 20;
    printf("%f\n", pow(x, y)); // error here, says no such function, however when pass the second argument in `pow` for the code runs by gcc, It works fine!
    return 0;
}

pow doesn't accept the second parameter to be a variable on gcc

The following code works fine on VC++10

// file test.cc
#include "stdafx.h"
#include <stdio.h>
#include <math.h>

int main(void)
{   
    double x = 10;
    int y = 20;
    printf("%f\n", pow(x, y));
    return 0;
}

But the following code doesn't not work on gcc:

// test.c
#include <stdio.h>
#include <math.h>

int main(void)
{   
    double x = 10;
    int y = 20;
    printf("%f\n", pow(x, y)); // error here, says no such function, however when pass the second argument in `pow` for the code runs by gcc, It works fine!
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

£烟消云散 2024-09-09 06:38:44

你错了。与第二个参数无关。

在 POSIXish 系统中,pow() 位于 libm 中,而在 win32ish 系统中,它是标准 C 库的一部分。 意味着

$ gcc program.c
/tmp/ccTw1gCA.o: In function `main':
program.c:(.text+0x30): undefined reference to `pow'

你需要这样做:

$ gcc program.c -lm

You're mistaken. It has nothing to do with the second parameter.

In POSIXish systems pow() is in libm, whereas in win32ish systems it is part of the standard C library. That means instead of this:

$ gcc program.c
/tmp/ccTw1gCA.o: In function `main':
program.c:(.text+0x30): undefined reference to `pow'

you need to do this:

$ gcc program.c -lm
_失温 2024-09-09 06:38:44

第二个参数看起来像常量而不是变量的原因是 gcc 有一个内置的 pow() 实现。如果第二个参数是常量,则可能会使用它,如果它是变量,则可能会使用 glibc pow() 函数。请参阅:

http://gcc。 gnu.org/onlinedocs/gcc-4.5.0/gcc/Other-Builtins.html#Other-Builtins

如果您将 -fno-builtin 传递给 gcc,您应该会看到一致的行为 -在这种情况下,无论您将什么传递给 pow(),都会出现错误消息。正如其他人提到的,每当您使用 math.h 中的任何内容时,您都需要与 -lm 链接。

The reason it may appear that the second parameter works as a constant but not as a variable is that gcc has a built-in implementation of pow(). If the second parameter is a constant it might be using that where if it's a variable it's falling back on the glibc pow() function. See:

http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Other-Builtins.html#Other-Builtins

If you pass -fno-builtin to gcc you should see consistent behavior--in this case error messages no matter what you pass to pow(). As others have mentioned whenever you use anything out of math.h you need to link with -lm.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文