In my Memory.hpp
file, I have a namespace boolean named isMHinit
:
namespace Memory
{
static bool isMHInit = false;
DWORD HookFunction(LPVOID pTarget, LPVOID pDetour, LPVOID pTrampoline, BOOL isWriteCopy);
static UINT64 CheckCodeAccess(UINT64 startaddress);
DWORD OnAccessHookFunction(PVOID pTarget, LPVOID pDetour, LPVOID pTrampoline, BOOL isWriteCopy);
}; // namespace Memory
And inside Memory.cpp
, I use and modify it:
// this function is a member of Memory, I removed most functionality for brevity.
DWORD HookFunction(LPVOID pTarget, LPVOID pDetour, LPVOID pTrampoline, BOOL isWriteCopy)
{
if (!isMHInit) {
if (MH_Initialize() != MH_OK) {
std::cout << "Error: MHInit failed." << "\n";
return 1;
}
isMHInit = true;
}
When going through clang-tidy, I get this warning, even though I clearly modify it inside the function:
Variable 'isMHInit' is non-const and globally accessible, consider making it const
Is this an issue with clang-tidy, or should I modify something in my code?
You should never declare a variable static
in a header (when it is not a class member). When a header contains
static bool isMHInit = false;
this means a separate variable isMHInit
in each *.cpp file where the header is included. If you want to have a globally accessible variable shared between all source files, you can declare it as
inline bool isMHInit = false;
However, using non-const globally accessible variables is poor design, and Clang-tidy warns you about it.
If you actually use the variable in a single source file only, then keep your declaration as is but move it to the *.cpp file. This makes the design a little better.