反正有没有跨编译单元隐藏C++类定义?
考虑,
//test1.cpp
struct local
{
local()
{
std::cout<<"test1::local\n";
}
};
void test1()
{
local l;
}
//test2.cpp
struct local
{
local()
{
std::cout<<"test2::local\n";
}
};
void test2()
{
local l;
}
//main.cpp
void test1();
void test2();
int main()
{
test1();
test2();
}
Run Code Online (Sandbox Code Playgroud)
它应链接和打印如下,
test1::local
test2::local
Run Code Online (Sandbox Code Playgroud)
我需要一个类似静态函数的机制,我不想使用命名空间或匿名命名空间,因为它仍然在目标文件中导出它的符号信息.
您可以使用匿名命名空间:
namespace {
struct local
{
local()
{
std::cout<<"test1::local\n";
}
};
}
void test1()
{
local l;
}
Run Code Online (Sandbox Code Playgroud)
这有效地将名称的范围限制在local使用它的翻译单元.(形式上这不正确,但如果你这样想,你就不会出错)