How to fix the “undefined reference to ‘pow’” error

The error “undefined reference to ‘pow’” can occur when trying to write a c/c++ program. So what exactly is “pow”? The “pow” is a function used in c or c++ which returns the power of a number. While using the pow function, you may encounter the error like “undefined reference to pow”. If you are looking for the solutions to this error, we have compiled this guide to serve the purpose.

What leads to “undefined reference to pow”?

It is a rather small error hence its reasons are very simple and they can be understood easily. This section will tell you some common reasons that invoke this error.

Reason 1: The Header file <math.h> is not imported

The first reason that you might be getting this error is that you have not imported the header file named <math.h> in your code. The function “pow” is part of this header file, therefore the absence of this header file will give you an “undefined” error.

Reason 2: The Argument (-lm) is not passed while compiling

Second most common reason for this issue occurs when compiling this code. While compiling the code, if the argument (-lm) is not passed, the program will return the “undefined reference to pow” error.

How to fix “undefined reference to ‘pow’”?

Keeping in view the reasons mentioned above, we have provided a distinctive solution to each reason.

Solution 1: Import the <math.h> header file

The <math.h> file should be imported in the program where the pow function is being used. Enter this header into your C program file using “#include”:

#include<math.h>

See the example below on how to insert the header:

Solution 2: Pass the (-lm) argument while compiling

To compile the program it is extremely important to make sure that we follow the correct syntax as well as include the (-lm) argument so that our code is linked with the maths library “libm.a”. Let us see how to write a command that will compile the file:

$ gcc -o example example.c -lm

The following is an example of the syntax to compile and run the c code:

Conclusion

The undefined reference to pow error is invoked if we miss the <math.h> header file or the program is not compiled correctly. To avoid this error, make sure you have included the header file and it is recommended to compile the program using the GCC with -lm argument. In this post, you have learned to fix the undefined reference to pow” error.