为什么我不需要包括main.cpp

Why do I not need to include main.cpp?

本文关键字:main cpp 包括 不需要 为什么      更新时间:2023-10-16

在小示例中,needsExtern.cpp需要global::bar的定义。cpp通常会包含带有定义的文件(在本例中为main.cpp)。但是,由于该文件是main.cpp,因此不需要它。

为什么needsExtern.cpp不需要包含main.cpp?

needsExtern.h

struct NeedsExtern
{
    NeedsExtern();
};

needsExtern.cpp

#include "needsExtern.h"
#include <iostream>
namespace global
{
    extern const int bar;
}
NeedsExtern::NeedsExtern()
{
    std::cout << global::bar << "n";
}

main.cpp

#include "needsExtern.h"
namespace global
{
    extern const int bar{26};
}
void main()
{
    NeedsExtern ne;
}

这正是extern被发明的原因:编译器只是假设变量是在项目的其他地方定义的。