How to compile a C program that uses math.h?

225,822

Solution 1

Append -lm to the end of your gcc command.

With all recent versions of GCC on GNU/Linux systems like Ubuntu, when you use the math library, you have to explicitly link to it. It is not automatically linked to along with the rest of the standard C library.

If you are compiling on the command-line with the gcc or g++ command, you would accomplish this by putting -lm at the end of the command.

For example: gcc -o foo foo.c -lm

Solution 2

If you are going to compile a C program with math.h library in LINUX using GCC or G++ you will have to use –lm option after the compile command.

gcc xyz.c -o xyz -lm

Here,

gcc is compiler command (compiler name)
xyz.c is a source file name.
-o is an option to specify the output file.
xyz is the name of the output file.
-lm is an option to link againt the math library (libm).

for more details here is the link containing complete article on it.
Compiling C program with math.h in Linux.

Share:
225,822

Related videos on Youtube

shreya
Author by

shreya

Updated on September 18, 2022

Comments

  • shreya
    shreya almost 2 years

    I am having problems in math.h header file and when I use square root function as in sqrt(d). But my compiler is not supporting this. Please advise me about this problem.

    My Ubuntu version is 2012.

  • mousomer
    mousomer over 7 years
    After the linking command, not the compile command. (Sorry for the nitpicking, but getting it right helps to understand other situations).
  • mr.loop
    mr.loop about 3 years
    @mousomer how to get it linking automatically [ubuntu 20.04]