C++ 编译器(或链接器?)如何知道如何处理 cpp 和 header class 文件?

How does the C++ compiler (or Linker?) knows how to handle cpp and header class files?

例如,我有一个 class Foo。我创建 Foo.hFoo.cpp,然后在 main.cpp 文件中包含 Foo.h。当我编译代码时,机器怎么知道关联 class header 文件和 class cpp 文件?是通过文件名完成的吗?
我真的很想了解这个编译和链接的过程。

When i compile the code how does the machine know to associate the class header file and the class cpp file? is it doing it by the files name?

不,编译器没有完成这种自动关联。

如果您有一个包含所有函数声明的头文件和 类,它必须是来自任何翻译单元(.cpp 文件)的 #included,它会使用它.
该步骤(声明合同)由 c 预处理器完成,其中 #include "MyDeclarations.hpp" 的每次出现都将其替换为翻译单元中 MyDeclarations.hpp 的完整文件内容。


一个简单的例子:

Foo.hpp

 class Foo {
 public:
      Foo(); // Constructor declaration
 };

Foo.cpp

 #include "Foo.hpp" // <<<< Include declarations

 Foo::Foo() {} // Constructor definition

main.cpp

 #include "Foo.hpp" // <<<< Include declarations

 int main() {
      Foo foo; // <<<<< Use declarations
 }

要最终指示您的链接器将所有这些文件拼接在一起,您必须参考 翻译单元 生成的工件。有点取决于工具链,但例如GCC 你可以使用一些编译器命令行,比如

 $ g++ main.cpp Foo.cpp -o myProg