未使用的变量警告,即使在IF语句中显式使用它时也是如此



我正试图创建(使用C++17(一个简单的调试标头,该标头仅在启用标志LOGGER_debug_MODE时执行某些代码行。这就是我的标题的定义方式(我也尝试使用{x;}而不是x,但警告仍然存在(:

debug.h

#ifndef _HDEBUG
#define _HDEBUG
static bool LOGGER_DEBUG_MODE = true;
#define R_DEBUG(x) if(LOGGER_DEBUG_MODE == true) x

#endif

我包含了debug.h,在代码的某个时刻,我调用宏函数R_debug来打印一些值:

logger_adc.cpp

double anlg_device_t::eval_formula()
{
double result = -9999;
try
{
result = parser.Eval();
}
catch (mu::Parser::exception_type &e)
{
std::cout << e.GetMsg() << std::endl;
}
R_DEBUG(std::cout << "Eval Result: " << result << std::endl);
return result;
}

我本以为一切都能正常工作,但当我运行makefile时,我收到了以下警告:

inc/debug.h:5:14:警告:已定义但未使用"LOGGER_debug_MODE"[-Wunused-variable]static bool LOGGER_DEBUG_MODE=true;

我以为我的定义搞砸了,但在检查了g++创建的临时文件后,似乎预处理器做了我预期的一切:

logger_adc.ii

double anlg_device_t::eval_formula()
{
double result = -9999;
try
{
result = parser.Eval();
}
catch (mu::Parser::exception_type &e)
{
std::cout << e.GetMsg() << std::endl;
}
if(LOGGER_DEBUG_MODE == true) std::cout << "Eval Result: " << result << std::endl;
return result;
}

为什么即使变量LOGGER_DEBUG_MODE明显在if语句中使用,我也会收到警告消息?我是不是搞砸了一些明显我没有注意到的东西?我的对象文件(发生警告的地方(的编译标志是g++ -Wall -Wextra -O1 -g -std=c++17 -save-temps=obj -Iinc -I/usr/local/include -cpkg-config --cflags --libs libmodbus

如果需要,这是我的主要功能:

main.cpp

#include "logger_adc.h"
int main()
{
anlg_device_t test (ADC_CHIP_1, 1, 18, 1, 1, true);
test.set_formula("2*x","x", test.get_voltage_ptr());
std::cout << "Test Voltage: " << test.get_voltage() << std::endl << "Test Relative: " << test.get_relative() << std::endl;
std::cout << "Test Formula (2*x): " << test.eval_formula() << std::endl;

return 0;
}

提前感谢!

您有一个定义static bool LOGGER_DEBUG_MODE =true;的标头。如果在多个C++文件中包含该标头,则每个文件都将获得该bool的自己的副本。

在main.cpp中,您没有使用R_DEBUG,因此该bool的副本(可能来自于包含logger_adc.h(在该文件中确实未使用。

可能的解决方案有:

您应该制作它,这样您就只有该bool的一个副本(用extern在标头中声明它,并在一个C++文件中定义它

使用构建定义而不是运行时检查

etc

最新更新