Search This Blog

How to Use Mathematical Functions in Math.h in GCC Compiler for C

Linux operating systems use GCC (GNU Compiler Collection). In recent versions versions of GCC, it is not enough to include the line #include<math.h> to use functions in math.h header file. The most commonly used functions in math.h are sqrt, pow, abs, sin, cos, tan, exp, log, log10, ceil, floor etc. If you use any of the functions defined  in math.h header file, even if you include the #include<math.h> pre-processor directive, the compiler may show an error. In such case you should manually link to math.h file. Suppose you are going to compile a file myfile.c which uses functions under math.h header, you may use the following commands in terminal for gcc:

gcc myfile.c -lm

or

gcc myfile.c -o outputfilename -lm

-l option is used to manually link libraries. -lm directs the compiler to manually link libm. So, if we use the math library, we have to manually link it in gcc compilers. It is said to be for the reason that earlier processors were slow and floating point capabilities were limited. It is also said that it is for the reason embedded computing components are not having much computing capabilities especially for floating point operations or some of them even do not need it. So, math.h is avoided from automatic linking.

No comments: