This question already has an answer here:
One definition rule and different class definitions in two translation units
                                
                                    (1个答案)
                                
                        
                                6年前关闭。
            
                    
例如,我有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);


我认为应该出现编译器错误,因为标头xxx.hiostream被包含两次:一次在f1.cpp中,一次在f2.cpp中。但是所有内容都已编译,因此我不知道它如何工作。

最佳答案

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

您还应该知道声明和定义之间的区别。声明某些内容时,您只是告诉编译器“该内容存在且类型为this-and-that”。定义内容时,您告诉编译器“这是我之前声明的内容”。

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

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

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

10-11 22:52
查看更多