C/C++ 头文件和实现文件:它们是如何工作的?

2022-01-04 00:00:00 compilation c++ header-files

这可能是一个愚蠢的问题,但我已经在这里和网上搜索了很长时间,但找不到明确的答案(我的尽职调查谷歌搜索).

This is probably a stupid question, but I've searched for quite a while now here and on the web and couldn't come up with a clear answer (did my due diligence googling).

所以我是编程新手...我的问题是,main 函数如何知道不同文件中的函数定义(实现)?

So I'm new to programming... My question is, how does the main function know about function definitions (implementations) in a different file?

例如.假设我有 3 个文件

ex. Say I have 3 files

  • main.cpp
  • myfunction.cpp
  • myfunction.hpp
//main.cpp

#include "myfunction.hpp"
int main() {
  int A = myfunction( 12 );
  ...
}

-

//myfunction.cpp

#include "myfunction.hpp"
int myfunction( int x ) {
  return x * x;
}

-

//myfunction.hpp

int myfunction( int x );

-

我知道预处理器如何包含头代码,但是头和主函数如何知道函数定义存在,更不用说使用它了?

I get how the preprocessor includes the header code, but how do the header and main function even know the function definition exists, much less utilize it?

如果这不是很清楚,或者我对某些事情有很大的误解,我很抱歉,这里是新的

I apologize if this isn't clear or I'm vastly mistaken about something, new here

推荐答案

头文件 declares 函数/类 - 即在编译 .cpp 时告诉编译器记录哪些函数/类可用.

The header file declares functions/classes - i.e. tells the compiler when it is compiling a .cpp file what functions/classes are available.

.cpp 文件定义了这些函数 - 即编译器编译代码并因此生成实际的机器代码来执行在相应的 .hpp 中声明的那些操作文件.

The .cpp file defines those functions - i.e. the compiler compiles the code and therefore produces the actual machine code to perform those actions that are declared in the corresponding .hpp file.

在您的示例中,main.cpp 包含一个 .hpp 文件.预处理器将 #include 替换为 .hpp 文件的内容.这个文件告诉编译器函数 myfunction 是在别处定义的,它接受一个参数(一个 int)并返回一个 int.

In your example, main.cpp includes a .hpp file. The preprocessor replaces the #include with the contents of the .hpp file. This file tells the compiler that the function myfunction is defined elsewhere and it takes one parameter (an int) and returns an int.

因此,当您将 main.cpp 编译为目标文件(.o 扩展名)时,它会在该文件中注明它需要函数 myfunction.当您将 myfunction.cpp 编译成目标文件时,目标文件中有一个注释,说明它具有 myfunction 的定义.

So when you compile main.cpp into object file (.o extension) it makes a note in that file that it requires the function myfunction. When you compile myfunction.cpp into an object file, the object file has a note in it that it has the definition for myfunction.

然后,当您将两个目标文件链接到一个可执行文件中时,链接器将最终联系起来 - 即 main.o 使用 myfunctionmyfunction.o.

Then when you come to linking the two object files together into an executable, the linker ties the ends up - i.e. main.o uses myfunction as defined in myfunction.o.

希望能帮到你

相关文章