Why do I not need to include main.cpp?

时间:2015-07-31 19:56:24

标签: c++ main

In the small example needsExtern.cpp needs the definition of global::bar. needsExtern.cpp would normally include the file with the definition (in this case main.cpp). However, since the file is main.cpp it is not needed.

Why does needsExtern.cpp not need to include 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;
}

1 个答案:

答案 0 :(得分:4)

This is precisely where extern is invented for: the compiler just assumes the variable is defined elsewhere in the project. You can read more about this principle here.

相关问题