在C++14标准中(我使用的是最接近的working draft, N3797),在"7.3 Namespaces"中,关于namespace有一句话,“Unlike other declarative regions, the definition of a namespace can be split over several parts of one or more translation units.” 而在"3.3.6 Namespace scope"中的第3条有如下说明:“The outermost declarative region of a translation unit is also a namespace, called the global namespace.” 这说明了平时我们用来说明“全局xxx”的“全局(global)”实际上是namespace的一个例子而已,而每个编译单元(源文件)的最外层的namespace都是global namespace,所以global namespace是天然跨多个文件的,从而了解一般namespace跨文件的行为最好的参照物是就是所谓“全局xxx”的行为——一言以蔽之,基本类似;一般情况下完全可以照搬。
举个例子,比如有如下两个文件:
/* file1.cpp */
#include <iostream>
namespace A
{
extern int b;
static int c = 7;
void print_values();
}
int main()
{
A::print_values();
}
/* file2.cpp */
#include <iostream>
namespace A