MPI Compilation Error : undefined reference to `sqrt’ – Solved

Updated on September 3, 2017

Question: Dear Techglimpse,  I’m trying to compile an MPI program (a simple example program which calculates PI value) using MPICH version 1.2.6. Below is the command that I used for compilation:

mpicc -o a.out pi.c

However, the command failed with an error message as “undefined reference to `sqrt’“. I verified the code and it has math.h defined. What could be the problem? – Surya

The detailed error message:

$ mpicc -o mpi-pi pi.c
/tmp/ccwuQwDw.o: In function `main':
pi.c:(.text+0x15f): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Solution:

Surya, you have to link math library during the compilation as shown below:

$ mpicc -o a.out pi.c -lm

The libm.so will be located under /usr/lib. However, the location might vary from machine to machine.

$ whereis libm.so
libm: /usr/lib/libm.so /usr/lib/libm.a

In option -lm, ‘l‘ points to prefix ‘lib’ and ‘m‘ for math.

Was this article helpful?

Related Articles

Leave a Comment