Search code examples
cmathgccgcc4

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


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;
}

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