Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc: why is the -lm flag needed to link the math library? [duplicate]

If I include <stdlib.h> or <stdio.h> in a C program I don't have to link these when compiling but I do have to link to <math.h>, using -lm with gcc, for example:

gcc test.c -o test -lm 

What is the reason for this? Why do I have to explicitly link the math library but not the other libraries?

like image 533
Nope Avatar asked Jun 23 '09 17:06

Nope


People also ask

What is the purpose of the flag when using GCC?

By default, GCC limits the size of functions that can be inlined. This flag allows the control of this limit for functions that are explicitly marked as inline (i.e., marked with the inline keyword or defined within the class definition in c++).

What is the purpose of the flag when compiling?

Compile-time flags are boolean values provided through the compiler via a macro method. They allow to conditionally include or exclude code based on compile time conditions. There are several default flags provided by the compiler with information about compiler options and the target platform.

What are the compiler flags?

Compiler flags are options you give to gcc when it compiles a file or set of files. You may provide these directly on the command line, or your development tools may generate them when they invoke gcc.

What is Ffast math?

-ffast-math, -fno-fast-math -ffast-math tells the compiler to perform more aggressive floating-point optimizations. -ffast-math results in behavior that is not fully compliant with the ISO C or C++ standard.


1 Answers

The functions in stdlib.h and stdio.h have implementations in libc.so (or libc.a for static linking), which is linked into your executable by default (as if -lc were specified). GCC can be instructed to avoid this automatic link with the -nostdlib or -nodefaultlibs options.

The math functions in math.h have implementations in libm.so (or libm.a for static linking), and libm is not linked in by default. There are historical reasons for this libm/libc split, none of them very convincing.

Interestingly, the C++ runtime libstdc++ requires libm, so if you compile a C++ program with GCC (g++), you will automatically get libm linked in.

like image 121
ephemient Avatar answered Sep 22 '22 17:09

ephemient