[英]Why do I not need to include main.cpp?
在小示例中,needsExtern.cpp需要定義global::bar
。 needsExtern.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
地方:編譯器僅假定變量在項目的其他位置定義。 您可以在此處閱讀有關此原理的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.