c++ - 为什么在多个 cpp 文件中包含相同的 header 然后它们的编译工作?

标签 c++ header-files

<分区>

比如我有2个cpp文件:f1.cpp和f2.cpp,还有一个头文件:xxx.h。

f1.cpp 具有以下源代码:

#include <iostream>
#include "xxx.h"

using namespace std;

int main ()
{
    rect rplace;
    polar pplace;
    cout<<"Enter the x and y values: ";
    while (cin>>rplace.x>>rplace.y)
    {
        pplace=rect_to_polar(rplace);
        show_polar(pplace);
        cout<<"Next two numbers (q to quit): ";
    }
    cout<<"Done.\n";
    return 0;
}

f2.cpp源码:

#include <iostream>
#include <cmath>
#include "xxx.h"

polar rect_to_polar (rect xypos)
{
    using namespace std;
    polar answer;
    answer.distance=sqrt(xypos.x*xypos.x+xypos.y*xypos.y);
    answer.angle=atan2(xypos.y, xypos.x);
    return answer;
} 

void show_polar (polar dapos)
{
    using namespace std;
    const double Rad_to_deg=57.29577951;
    cout<<"distance="<<dapos.distance;
    cout<<", angle= "<<dapos.angle*Rad_to_deg;
    cout<<"degrees\n";
}

和xxx.h:

struct polar
{
    double distance;
    double angle;
};

struct rect
{
    double x;
    double y;
};

polar rect_to_polar (rect xypos);
void show_polar(polar dapos);

我认为应该是编译器错误,因为 header xxx.hiostream 包含两次:一次在 f1.cpp 中,一次在 f2.cpp 中.但是一切都是编译的,所以我不明白它是如何工作的。

最佳答案

预处理器简单地读取头文件并将它们放入#include 指令所在的翻译单元中。如果一个头文件包含在一个源文件中,则只有该文件知道该头文件中的声明。

您还应该了解声明定义 之间的区别。当您声明 某些东西时,您只是告诉编译器“这个东西存在并且是这样那样的类型”。当您定义某些东西时,您告诉编译器“这是我之前声明的东西”。

同一事物可以有多个声明。因为它们只充当编译器的元数据,不在其翻译单元之外使用。但是,您只能对某物有一个定义。这就是为什么不能在包含在多个源文件中的头文件中定义全局变量/函数的原因。

另外,在这个回答中我谈到了“源文件”、“头文件”和“翻译单元”。头文件是您#include 的文件。源文件是执行包含(可以这么说)的文件。翻译单元是完整的预处理源,包括源和所有包含的头文件,并传递给实际的编译器。

关于c++ - 为什么在多个 cpp 文件中包含相同的 header 然后它们的编译工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20023346/

相关文章:

c++ - 函数生成不正确的装饰名称

c++ - 从 Ubuntu 中的 Qt GUI 应用程序运行多个命令行应用程序并获取控制台输出

c++ - "type"使用 C++ 的表情符号

c - 为什么头文件可以包含自身?

c++ - 从同一目录读取图像?

c - 系统头文件和普通头文件 gcc

通过 typedef 定义 C++ 新类型

c++ - 帮助我理解 std::erase

c++ - 为什么执行矩阵乘法的两个进程并行运行比连续运行慢?

c - 将静态函数分离到 C 中的另一个(头文件?)文件中