A mock with the same name in a different compilation unit can result in runtime crash

163 views
Skip to first unread message

Kieran D'Archambaud

unread,
Jul 14, 2011, 8:48:24 AM7/14/11
to Google C++ Mocking Framework
Hi,

I have just started using Google mock and ran into a small issue.

What steps will reproduce the problem?
1. Create a mock
2. Create another mock with the same name in a different compilation
unit
3. At runtime, using the mock can result in runtime crash

What is the expected output? What do you see instead?
Compile time error if two mocks have the same name, or at the very
least a user readable runtime assert.

What version of the product are you using? On what operating system?
1.5.0, Win64

Please provide any additional information below.
Only crashed in debug, not release in test code. It crashed inside the
first call to EXPECT_CALL.

Now I know the issue, it is an easy fix, but it would be fantastic if
it was either made impossible via a compile time error, or obvious
what had happened via a runtime assert.

Thanks,
Kieran

Keith Ray

unread,
Jul 14, 2011, 1:44:17 PM7/14/11
to Kieran D'Archambaud, Google C++ Mocking Framework
use anonymous namespaces to avoid this problem.

FileA.cpp
=================================
#include <gmock.h>

namespace {
// the usual mocking and test code here
}
=================================

FileB.cpp
=================================
#include <gmock.h>

namespace {
// the usual mocking and test code here, even using same names as FileA.cpp
}
=================================

--
C. Keith Ray

Coach, Trainer, and Developer at Industrial logic, Inc.
http://industriallogic.com  "Amplify Your Agility"
Coaching and Live and Web-based Training

Kieran D'Archambaud

unread,
Jul 27, 2011, 4:23:09 AM7/27/11
to Google C++ Mocking Framework
Thanks for the reply, and that does indeed stop the issue.

However, in my opinion it would be a good addition to make Google Mock
assert in debug builds if you try and register a mock of the same
name. Anything which is used as part of a testing framework should be
bulletproof in my opinion so that any issues that show up clearly
point to an issue in the client's code.

Thanks,
Kieran
> Coach, Trainer, and Developer at Industrial logic, Inc.http://industriallogic.com "Amplify Your Agility"

Zhanyong Wan (λx.x x)

unread,
Aug 8, 2011, 1:15:56 PM8/8/11
to Kieran D'Archambaud, Google C++ Mocking Framework
Unfortunately there really is nothing googlemock can do here.

What you did is called a "one-definition rule violation" in C++. The
C++ standard says that it's undefined behavior, and the compiler is
free to generate code that does anything it likes. The linker is not
required to diagnose this error. There's no way for googlemock to
know that an ODR violation has happened.

On Wed, Jul 27, 2011 at 1:23 AM, Kieran D'Archambaud

--
Zhanyong

Reply all
Reply to author
Forward
0 new messages