Notice! This document is currently in Archived status.
The content of this document may be incorrect or outdated.

Print this article Edit this article

Using the C Math Library

Purdue Engineering Computer Network
There is a library of C functions called the "mathematics library" for performing many common math functions. There are functions such as sqrt, pow, sin, cos, sinh, tanh, etc. You can get a listing of the available functions by using the man command's -k option:
	% man -k 3m
To learn more about any particular math function, again use the man command to view the individual manual page. For example, to see the man page for the sqrt function, type this:
	% man sqrt
You can also type:
	% man math
for a list of many available functions, as well as details about the mathematics behind them and information on rounding errors, precisions, and so on.

When using the math functions in your C program, you need to do several things:

  • Functions have to be declared in the program. Function declarations are kept in header or include files, which are installed in /usr/include with .h suffixes.

    For example, if you need to take the square root of a number in your program, you need to use the sqrt function. This function resides in the Math library. This means that you need to link the program with libm.a and you need to read in the math.h header file (which declares sqrt). So in the program you need to have the following line near the top of the source file:

    	#include <math.h>
  • Link with the math library when compiling your program. If you use functions that are defined in libraries (and you most definitely will), you need to make sure that when the program is compiled, it is linked to the libraries it needs. You also have to make sure the proper header files are read by your program, since the program won't compile unless all functions have been declared.

    So, when you compile the program, you need to use the -l command-line option to link with libm:

    	% cc program.c -lm
Make sure the -lm option is the last item on the line. A common mistake is to forget this option when compiling, which results in error messages informing you that the math functions are undefined.

Last Modified: Dec 19, 2016 11:12 am US/Eastern
Created: Aug 22, 2007 11:13 am GMT-4 by admin
JumpURL: