Search code examples
c++googletestgooglemock

Two objects with the same name in the same namespace in different cpp files


I've used MATCHER_P from gmock to create some matchers in different *.cpp test files. They happened to be defined in the same namespace and had the same name. When running the tests, I've got a segfault, because a test from fooTest.cpp used a matcher from barTest.cpp, even though a matcher with the same name was declared in fooTest.cpp and barTest.cpp was obvoiusly not included.

What is going on here? Why does the test from fooTest.cpp even see the matcher declared in barTest.cpp? Shouldn't it be confined to the scope of the file that it's declared in? And if not why am I not getting a compilation error that says something about an "ambiguous call?"


Solution

  • Using my crystal ball, your problem is that you have to identically named inline methods or functions. Functions defined in the body of a class are implicitly inline.

    When you have two different inline functions with the same name, the linker silently discards all but one of them. Such names include the names of the class they are part of.

    If the implementation of one or the other is different, this leads to problems. One classic problem is inlined non-trivial zero argument constructors for objects of different size; one of them is discarded, and now you are clearing the wrong amount of memory for the wrong class.

    This could be laid at the feet of a one definition rule violation -- the very existence of your two classes is a ODR violation and makes your program ill formed, no diagnostic required.

    But knowing the step that actually caused your program to keel over is useful.

    The fix this this is to always define everything in a cpp file within an anonymous namespace. Anything that defines a symbol in a header file should fully qualify it. Now no definitions in one cpp file can collide with definitions in another accidentally.