简体   繁体   中英

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.

In FileA.cpp there is also a static variable defined. In another file say FileB.cpp there is a usage of this static variable.

My existing Unit Test code does not reference FileA.cpp, since none of its functionality is being tested so far. It does however test functionality of 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).

But now I need to test FileA.cpp. When I add the file in the Makefile, I am getting a "multiple definition" error for this static variable.

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. 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.

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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