问题描述
我有一个关于图书馆的问题。当我编写一个库时,我有两个文件: library.h
和 library.cpp
。
第一个包含函数的原型,第二个包含定义。那么,在 library.cpp
中包含 #includelibrary.h
,所以它们以一种方式连接,但是头部会发生什么?为什么我不必在头文件中写 #includelibrary.cpp
?
当我使用在主文件中的库中,我写了 #includelibrary.h
,其中包含原型,但编译器如何知道定义在哪里?
简要解释:
$ b .cpp 文件被发送到预处理器。
(2)预处理器读取 #include 行。 h
,并找到文件 library.h
。
library.h
的内容直接复制到 library.cpp
文件中。
(4)编译 library.cpp
文件并链接到主文件。
因此,标题中的所有原型都被复制到实现文件的顶部。编译并链接 .cpp
文件。头文件本身没有被编译 - 它们的内容被复制到 .cpp
文件中。
I have a question about libraries. When I write a library I have 2 files: library.h
and library.cpp
.
The first one contains the prototypes of the functions and the second one contains the definitions. Well, in library.cpp
I include #include "library.h"
, so they are connected in one way, but what happens with the header? Why don't I have to write #include "library.cpp"
in the header?
When I use the library in the main file, I write #include "library.h"
, which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly:
(1) Your library.cpp
file is sent to the preprocessor.
(2) The preprocessor reads the line #include "library.h"
and goes and finds the file library.h
.
(3) The contents of library.h
are literally copied into the library.cpp
file.
(4) The library.cpp
file is compiled and linked with the main file.
Thus, all of the "prototypes" in the header are copied into the top of the implementation file. .cpp
files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the .cpp
files.
这篇关于为什么我不需要在头文件中包含library.cpp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!