alexander.sivak
alexander.sivak

Reputation: 4730

CppCheck ignores the usage of variables in macro definitions, how to change that?

The output of running CppCheck on my code displays the following error: Variable 'strFullPath' is assigned a value that is never used. [unreadVariable]

The method below is the one in discussion.

void DebugLogging::GetDebugLogSettings(const std::string& sAppProfile)
{
    std::string strFullPath = ROOT_KEY_NAME + sAppProfile;
    
#ifdef _WIN32
    std::string strFullPathLocal = strFullPath + "Local";
#else
    std::string sAppProfileLocal = sAppProfile + "Local";
    std::ifstream settingsLocalfile(sAppProfileLocal.c_str());
#endif
}

CppCheck states that strFullPath's value is never used. However, it is used inside a macro.

How to setup CppCheck so it becomes capable of finding the usage of the variable?

Upvotes: 1

Views: 840

Answers (2)

Daniel Marjamäki
Daniel Marjamäki

Reputation: 3037

I am a Cppcheck developer. The fix Damian-Teodor Beles suggested is nice.

I just wanted to add some philosophy. In my humble opinion that particular warning is unfortunate. I consider it a false positive, as a human I can see that the value is used.

This false positive can be fixed in Cppcheck. We have fixed some related false positives but obviously not this one. It might be fixed in Cppcheck in the future but I can't promise when that would happen.

In general I assume that moving the variable is a nice fix. But maybe sometimes you don't want to move the variable. Then you could inline suppress the warning for now. When we fix this in Cppcheck, you will get a warning that says that the inline suppression is never used.. and then you can remove the comment.

Upvotes: 1

Damian
Damian

Reputation: 1374

Move it inside the macro.

void DebugLogging::GetDebugLogSettings(const std::string& sAppProfile)
{
#ifdef _WIN32
    std::string strFullPath = ROOT_KEY_NAME + sAppProfile;
    std::string strFullPathLocal = strFullPath + "Local";
#else
    std::string sAppProfileLocal = sAppProfile + "Local";
    std::ifstream settingsLocalfile(sAppProfileLocal.c_str());
#endif
}

Upvotes: 1

Related Questions