2

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?

Community
  • 1
  • 1
  • possible duplicate of [Why do you have to link the math library in C?](http://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c) – jxh Aug 22 '14 at 03:50
  • 1
    In the first case, the compiler is able to evaluate `pow()` at compile time; without an actual call, the math library is not needed. In the second, the compiler generates an actual call. The math library is not linked by default (at least for the compiler you're using). – Keith Thompson Aug 22 '14 at 05:25
  • **g++ -lm -o test_1 test_1.cpp**. I have linked math library using above command. It still shows the same error. – Tarun Vashisth Aug 22 '14 at 07:01
  • Can you try `g++ -o test_1 test_1.cpp -lm` ? Some linkers think it doesn't really need to link `libm` before it really sees unresolved symbols in `test_1.cpp`. – nodakai Aug 22 '14 at 07:11
  • I have tried `g++ -o test_1 test_1.cpp -lm` too. Still same error. To give you more information on my stdam.h file(which is designed to restrict some functionalities )....Here is how pow() is defined in it...`#ifndef _MATH_H_ #define _MATH_H_ double pow ( double , double); #endif` . – Tarun Vashisth Aug 22 '14 at 07:33

1 Answers1

1

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"

Community
  • 1
  • 1
Icarus3
  • 2,310
  • 14
  • 22