如何隔离两个同名的c++ 类?
How to isolate two c++ classes with the same name?
我有一个包含一堆 C++ 测试文件的项目。每个测试文件声明一个 class 像这样:
// test1.cpp
...
class Foo { void bar() {...} };
...
和
// test2.cpp
...
class Foo { void bar() {...} };
...
等等。
一切都很好,直到测试套件变得相当大并且 Foo
class 的内容在某些测试模块中变得不同。当涉及到链接时,事情就出错了。每个 ELF 文件中 class 的方法被声明为 public 弱("W" 在 nm
符号中)符号,它会导致调用错误的方法实例,例如tests1.cpp
从 tests2.cpp
调用 Foo::bar()
。
如何将 class Foo
的一个实例与另一个实例隔离开来?
用 __attributes__ ((visibility ("hidden")))
声明 class 没有帮助,符号仍然是 public。
我当然可以为此使用名称空间,但我宁愿避免使用此选项。
有什么想法吗?
您对命名空间的怀疑是您不想给它们赋予任意名称,这是没有根据的。
这是匿名命名空间 的完美工作。写入
namespace /*no name here makes it anonymous*/{
class Foo { void bar() {...} };
}
等等。这样做会将 Foo
内化到那个特定的翻译单元。
我有一个包含一堆 C++ 测试文件的项目。每个测试文件声明一个 class 像这样:
// test1.cpp
...
class Foo { void bar() {...} };
...
和
// test2.cpp
...
class Foo { void bar() {...} };
...
等等。
一切都很好,直到测试套件变得相当大并且 Foo
class 的内容在某些测试模块中变得不同。当涉及到链接时,事情就出错了。每个 ELF 文件中 class 的方法被声明为 public 弱("W" 在 nm
符号中)符号,它会导致调用错误的方法实例,例如tests1.cpp
从 tests2.cpp
调用 Foo::bar()
。
如何将 class Foo
的一个实例与另一个实例隔离开来?
用 __attributes__ ((visibility ("hidden")))
声明 class 没有帮助,符号仍然是 public。
我当然可以为此使用名称空间,但我宁愿避免使用此选项。
有什么想法吗?
您对命名空间的怀疑是您不想给它们赋予任意名称,这是没有根据的。
这是匿名命名空间 的完美工作。写入
namespace /*no name here makes it anonymous*/{
class Foo { void bar() {...} };
}
等等。这样做会将 Foo
内化到那个特定的翻译单元。