Librariesare collections of precompiled functions that have been written to be reusable. Typically, they consist of sets of related functions to perform a common task.
Firstly, think of both like this (a analogy) :
- The header is a phone number u can call, while ...
- The library is the actual person u can reach there.
It's the similar difference between "interface" and "implementation"; theinterface (header) tells youhow to call some functionality (without knowing how it works), while theimplementation (library) is the actual functionality.
Advantages:
1. It allows your flexibility: you can have the same header for different libraries (i.e. the functionality is exactly called in the same way), and each library mayimplement the functionality in a different way. By keeping the same interface, you can replace/revise the libraries without changingyour calling codes.
2. By putting each function in it's own .c file, you can reduce your overall build times by only recompiling the files thatneed to be recompiled.
3. Avoid linker errors: You can't put functiondefinition in the header files. If later you would
#include
this header in to more then one c file, both of them would compile the function implementation into two separate object files. The compiler would work well, but when the linker wanted to link together everything, it would findtwo implementation of the function and would give you an error.
#gcc -c util.c#ls *.outil.o
Header (my_header.h):void
foo(
int
);
int
bar(
char
*,
int
);
Source file (Program.c):#include "my_header.h"
void
my_function()
{
int
blah = 10;
char
array[8];
/* Call other functions */
foo(blah);
}
#include
simple takes the header file and replaces the #include
line with the contents of the file. When you go to compile this, the preprocessor first takes care of its business and generates an intermediate file with the contents of the
header pasted into the source file as such:Code:void
foo(
int
);
int
bar(
char
*,
int
);
void
my_function()
{
int
blah = 10;
char
array[8];
/* Call other functions */
foo(blah);
bar(array,
sizeof
(array));
}
$gcc -c program.c# 源程序对象文件和库对象文件进行链接$gcc -o program program.o util.o$./program