简体   繁体   English

使用C ++中的Link Seam打破静态变量依赖性

[英]Break static variable dependency using Link Seam in C++

I am trying to write a Unit Test for a function. 我正在尝试为功能编写单元测试。 This function is static and in a file, say FileA.cpp, though it is not a member of any class. 该函数是静态的,位于文件(例如FileA.cpp)中,尽管它不是任何类的成员。

In FileA.cpp there is also a static variable defined. 在FileA.cpp中,还定义了一个静态变量。 In another file say FileB.cpp there is a usage of this static variable. 在另一个文件FileB.cpp中,有此静态变量的用法。

My existing Unit Test code does not reference FileA.cpp, since none of its functionality is being tested so far. 我的现有单元测试代码未引用FileA.cpp,因为到目前为止尚未对其功能进行测试。 It does however test functionality of FileB.cpp. 但是,它确实测试了FileB.cpp的功能。 To facilitate this static variable reference, a fake variable is defined in Main.cpp of the Unit Test project (I am using GoogleTest framework). 为了方便进行此静态变量引用,在单元测试项目的Main.cpp中定义了一个伪变量(我正在使用GoogleTest框架)。

But now I need to test FileA.cpp. 但是现在我需要测试FileA.cpp。 When I add the file in the Makefile, I am getting a "multiple definition" error for this static variable. 当我在Makefile中添加文件时,此静态变量出现“多个定义”错误。

I tried introducing a .h file (Say GlobalVars.h) with the same name in the Production and Testing project respectively and moving the variable there but it does not seem to fool the compiler. 我尝试在生产和测试项目中分别引入一个具有相同名称的.h文件(Say GlobalVars.h),然后将变量移到该文件中,但这似乎并没有使编译器蒙上阴影。 The FileA.cpp instance in the test project still tries to access the GlobalVars.h of the production code and I get a double definition again. 测试项目中的FileA.cpp实例仍然尝试访问生产代码的GlobalVars.h,我再次得到一个双重定义。

Any ideas how could I break this dependency? 有什么想法可以打破这种依赖性吗?

Instead of static variables, you should use variables defined inside an anonymous namespace. 代替静态变量,您应该使用在匿名名称空间中定义的变量。 Those can be used as static global variable would be in a translation unit, but they have the advantage to be invisible outside the translation unit, not breaking the One Definition Rule. 那些可以用作静态全局变量,但可以在转换单元之外看到它们,而不会违反“一个定义规则”,因此它们可以在转换单元中使用。

// a.cpp
static int count = 0;
void f() { ++count; }

// b.cpp
static int count = 100; // breaks ODR
int g() { return count--; }

becomes

// a.cpp
namespace { int count = 0; }
void f() { ++count; }

// b.cpp
namespace { int count = 100; } // OK
int g() { return count--; }

Further reading: 进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM