[英]What is the difference between header and library file?
I am really confused about this.我真的很困惑。 I can't understand how code from library files is linked with a header file.
我不明白库文件中的代码如何与 header 文件链接。 Can anyone please help me?
谁能帮帮我吗?
Forget about header files for a second, and look at the following program:暂时忘记 header 文件,看看下面的程序:
// Forward declare foo()
void foo();
int main() {
foo();
return 0;
}
I can compile this program fine, but if I try to link it, I'll get an error along the lines of:我可以很好地编译这个程序,但是如果我尝试链接它,我会收到如下错误:
I was promised that a function called
foo()
exists, but I can't find it anywhere.我被承诺存在一个名为
foo()
的 function,但我在任何地方都找不到它。
Now, if I link the same program against a library that happens to provide the foo()
function then it'll be fine.现在,如果我将相同的程序链接到恰好提供
foo()
function 的库,那么它会没事的。
The header is just a formal way of packaging all the forward declarations of a library (and some other stuff) in a way that accurately documents the content of a library. header 只是一种以准确记录库内容的方式打包库(和其他一些东西)的所有前向声明的正式方式。 But that's just a convention.
但这只是一个约定。 As long as the forward declarations are visible to the compiler from somewhere , then that's all that is actually required.
只要编译器从某个地方可以看到前向声明,那么这就是实际需要的全部。
Remember: #include "path/to/file.h"
literally means "copy paste the content of that file here."记住:
#include "path/to/file.h"
字面意思是“复制粘贴该文件的内容到这里”。
So this is pretty much the same thing as my original program:所以这和我原来的程序差不多:
//foo.h
void foo();
//main.cpp
#include "foo.h"
int main() {
foo();
return 0;
}
The.lib files contain all the code of each function that was put in it. .lib 文件包含放入其中的每个 function 的所有代码。 The header file contains the function declarations so that the compiler knows what the functions are.
header 文件包含 function 声明,以便编译器知道函数是什么。
If you have the following function in the library file:如果库文件中有以下 function:
int myFunction(char c, int a) {
//... Do something
}
The header file will contain the declaration: int myFunction(char c, int a)
The.lib file will contain the //... Do something part
header 文件将包含声明:
int myFunction(char c, int a)
The.lib 文件将包含//... Do something part
The.lib is only use during compiling and serves no purpose at runtime because its contents (those that are used) will be put into the executable file. .lib 仅在编译期间使用,在运行时没有任何用途,因为它的内容(使用的内容)将被放入可执行文件中。
For more information:了解更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.