Search code examples
c++referenceg++undefinedpow

Linker error on calling pow() when one argument is return value of a function


Consider the code below:

    #include "../datatypes/stdam.h"
    using namespace std;

    int main(){
    int val = pow(pow(3,2),2);
    cout << val;
    return 0;
    }

Here, stdam.h header allows me to use pow() and cout functionality. Now when I run the code above, the output is 81 which is as expected. Now consider small modification of above as shown below:

    #include "../datatypes/stdam.h"
    using namespace std;

    double testing() {
       return pow(3,2); 
    }

    int main(){
    int val = pow(testing(),2);
    cout << val;
    return 0;
    }

Now when I run the last code, compiler throws following error:

 /tmp/ccxC17Ss.o: In function `main':
 test_1.cpp:(.text+0x2f): undefined reference to `pow(double, double)'
 collect2: ld returned 1 exit status

Where am I going wrong? What causes the error above?


Solution

  • Change your header as:

    #ifndef _MATH_H_
    #define _MATH_H_
    
    extern "C"
    double pow( double x, double y );
    
    #endif
    

    You really should include math.h or cmath

    Anyway, see In C++ source, what is the effect of extern "C"? for significance of extern "C"