We have an existing Mutex
C++ class. It has a debug feature to track the owner thread id. So it has a member variable to store this, but because the original developer doesn’t want to waste memory, this member is wrapped by a macro in a header file.
This header file has been included in multiple projects, some binaries are developed by other departments, so for those libraries we cannot control the compile flag switch, and we do not want this strong coupling.
// mutex.h
class Mutex
{
......
private:
#ifdef _DEBUG
int owner_thread_id_;
#end
......
}
Recently we were bitten by this code, because of memory corruption caused by violating the one definition rule.
So how can we implement it with following two requirements:
- Don’t waste memory because it is a utility class and wide used.
- Don’t violating the one definition rule.
6
Simply. Don’t mix code built with debug with code built without.
If that class is exported by library you link against, you either need to:
- Have debug and release version of the library. That’s what one always does on Windows where even the standard runtime has such two versions and they are incompatible, so there is no other way in most cases. This is also the only option if it’s third party library you can’t fix.
- Create debug flag specific to the library and keep a configuration header around setting it as appropriate for the way you built the library.
- Leave the field in unconditionally and only make the check conditional (and make sure the all relevant functionality is in functions that get compiled into the library, i.e. defined in .cpp files).
- Convert the class to use the PImpl idiom. Then the private fields don’t affect ABI.
Ad Edit 1: To prevent linking against the library compiled with different flags than the client code you need to make some symbols be called differently depending on the flag (_DEBUG).
In C++ most suitable method seems to be putting some code in a subnamespace, make that subnamespace be called differently in debug and release configuration, i.e. something like
#ifdef _DEBUG
namespace library_internal_debug
#else
namespace library_iternal_release
#endif
and then import the symbols to the main namespace with similarly conditional using:
namespace library {
#ifdef _DEBUG
using library_iternal_debug::stuff;
#else
using library_iternal_release::stuff;
#endif
That way the client will use library::stuff
in either configuration, but the actual symbol names will differ, so linking against incorrect build will fail. And unlike renaming with preprocessor this will be properly scoped.
You only need to apply it to one or few important symbols.
4