I am working on a legacy C++ code with two libraries. Library1 is the main and Library2 uses classes from Library1 (so there are some #includes "HeaderFromLibrary1" in Library2).
Deep in the code of Library1, there is some work done and when something happens I need to set a boolean variable. Library2 has to be able to get this value and reset it.
All code is object-oriented, so there are no global variables nor C-functions, but only classes objects.
What would be the best way to be able to modify this boolean variable from these libraries?
What I did is, I created two new files in Library1: SharedData.cpp and SharedData.h.
SharedData.h
#ifndef SHARED_DATA_H_
#define SHARED_DATA_H_
namespace MyNameSpace
{
/*
* Get the Boolean and reset it to FALSE.
*/
boolean GetAndResetBoolean(void);
/*
* Set the Boolean.
*/
void SetBoolean(void);
}
#endif
SharedData.cpp
#include "util/SharedData.h"
#include "Mutex.h"
namespace MyNameSpace
{
static Mutex mutexBoolean;
static boolean myBoolean;
/**
* Method used to set the boolean.
*/
void SetBoolean(void)
{
ScopedLock lock(mutexBoolean);
myBoolean= TRUE;
}
/**
* Method used to get and reset the Boolean.
*/
boolean GetAndResetBoolean(void)
{
ScopedLock lock(mutexBoolean);
boolean currentBoolean = myBoolean;
myBoolean = FALSE;
return currentBoolean;
}
}
So I include the SharedData.h in the file I need to set the boolean (Library1) and also in the file I need to get the value and reset it.
I do not like that I have to create 2 "global" variables. I would prefer to store the boolean in an object, but the lifetime of the object that sets the boolean is not very long. And I do not want to include any HeaderFromLibrary2.h in Library1 because Library2 uses Library1 and not the other way around.
Do you have any recommendation?