In this post you will learn about C C++ library (aka object or archive) files. I assume you have a basic knowledge of programming in Linux and good knowledge of the C C++ basics. In brief libraries make programming easy by reducing compile time and allowing re-usability of functionalities. Soon you will find how this is done. Have a look at the following C/C++ program to find square root of a number.
/* www.techybook.in - Sample code 8.1 */ #include <math.h> #include <stdio.h> int main() { int I=100; while(I--) printf("Sqrt: %f\n", sqrt(I)); return 0; }
Save it as sqrt.c Now when you try to compile this code with the usual command `$> gcc sqrt.c -o sqrt` you will get the following error in your Linux machine
$> sqrt.c:(.text+0x39): undefined reference to `sqrt' $> collect2: ld returned 1 exit status
If you analyze these error soon you will find that the solution for this is to use the following compile command `$> gcc sqrt.c -o sqrt -lm` The difference between the previous and the current compile command is `-lm` flag.
What does this -lm means?
– : means the following is a compiler flag
l : link
m : name of the library
The flag internally expands to `libm.a` and tells the gcc compiler to look in the file libm.a while linking for the functions used in the program. In our case it looks for the definition of the function `sqrt()`