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
#includethis 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):voidfoo(int);intbar(char*,int);Source file (Program.c):#include "my_header.h"voidmy_function(){intblah = 10;chararray[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:voidfoo(int);intbar(char*,int);voidmy_function(){intblah = 10;chararray[8];/* Call other functions */foo(blah);bar(array,sizeof(array));}
$gcc -c program.c# 源程序对象文件和库对象文件进行链接$gcc -o program program.o util.o$./program
C/C++的库文件包含预编译的可重用函数,而头文件则提供调用接口。头文件类似于电话号码,定义了如何调用功能,而库文件则是实际实现功能的部分。这种分离提供了灵活性,允许使用相同的接口替换不同实现的库,减少了编译时间,并避免链接错误。
3062

被折叠的 条评论
为什么被折叠?



