N Kaushik

Fix - Undefined reference to 'pow' error in Linux

January 27, 2022

Undefined reference to ‘pow’ error in Linux:

The pow function is used to find the power of a number in C/C++. This is defined in the math.h header file.

If you are running a C/C++ program using gcc/g++ in a linux system, you might face this error:

Undefined reference to 'pow'

Before I show you how to fix this, let’s learn what is pow function and how to use it.

Definition of pow:

The pow function is defined as like below:

double pow(double b, double p)
  • This function is used to find the power of a number.
  • b is the base and p is the power.

This is a quick and easy way to find the power of one number. We can write a function to find the power. But, since this is already available, we can use it instead of writing another function.

To use pow, we need to import math.h header file. So, at the top of your program, you need to add this:

#include<math.h>

Once it is added, you can use pow.

Example of pow:

Let me show you an example of pow and how it works. Create a new file example.c and copy-paste the below code:

#include <stdio.h>
#include <math.h>

int main()
{
    printf("%f", pow(2, 4));

    return 0;
}

Here,

  • We are printing the value of pow(2, 4)
  • Note that math.h is imported at the top of the program.

If you run this program, it will print the below output:

16.000000

But, in linux, you might face the above error Undefined reference to pow function. This is a common error and you will find it mostly in linux.

Let me explain to you the reason of this error and how to fix it.

Reason:

The main reason of this issue is that the definition of the pow function is not found. If you are adding math.h to the program file, you are adding the declaration of the pow function. But it doesn’t adds the definition of pow. So, the compiler will not find the definition and it will throw an error that undefined reference to pow function. That’s all.

Solution of undefined reference error:

First of all, check if math.h is included to the program or not. You might also get some different error as like below if this header file is not added:

note: include the header <math.h> or explicitly provide a declaration for 'pow'

The definition of pow is stored in a libm.a library file in Linux. Its location is /usr/lib/libm.a.

We need to link this library file with the compiled program. We can do it in two different ways:

  1. We can directly pass the path of libm.a while compiling:
gcc example.c /usr/lib/libm.a
  1. Or, we can simply use -lm flag:
gcc example.c -lm

You can use any of these two ways to fix this issue. The recommended way is to use the -lm flag instead of passing the full path.


Subscribe to my Newsletter