Question

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;
}
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top