C ++编译器(或Linker?)如何知道如何处理cpp和头文件类文件? [英] How does the C++ compiler (or Linker?) knows how to handle cpp and header class files?

查看:264
本文介绍了C ++编译器(或Linker?)如何知道如何处理cpp和头文件类文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个类Foo。我创建 Foo.h Foo.cpp 然后我包括 Foo.h main.cpp 文件中。当我编译代码,机器怎么知道关联类头文件和类cpp文件?是由文件名完成的吗?

我真的很想了解这个编译和链接过程。

For example, I have a class Foo. I create Foo.h, Foo.cpp and then I include Foo.h in the main.cpp file. When I compile the code, how does the machine know to associate the class header file and the class cpp file? Is it done by the filenames?
I'm really interested in understanding this process of compilation and linking.

推荐答案


当我编译代码如何机器知道关联类头文件和类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?

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

No, there's no such kind of automatic association done by the compiler.

如果你有一个包含函数和类的所有声明的头文件,它必须是来自任何翻译单元的 #included code> .cpp 文件),使用它。

该步骤(声明合约)由c预处理器完成,其中每次出现 #includeMyDeclarations.hpp替换翻译单元中 MyDeclarations.hpp 的完整文件内容。

If you have a header file containing all the declarations of functions and classes, it must be #included from any translation unit (.cpp file), that makes use of it.
That step (of declaration contracts) is done by the c-preprocessor where every occurrence of #include "MyDeclarations.hpp" replaces that with the complete file content of MyDeclarations.hpp in the translation unit.

一个简单的例子:

Foo.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你可以使用一些编译器命令行像


To finally instruct your linker to stich all of these files together you have to refer to the artifacts produced from the translation units. Depending on the toolchain a bit, but for e.g. GCC you may use some compiler command line like

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

这篇关于C ++编译器(或Linker?)如何知道如何处理cpp和头文件类文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆