gcc警告:已定义但未使用与未使用的变量 [英] gcc warnings: defined but not used vs unused variable

查看:986
本文介绍了gcc警告:已定义但未使用与未使用的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我编译代码时,都会观察到以下两个警告:

Whenever I compile my code I observe following two warnings:

warning: '<variable>' defined but not used
warning: unused variable '<variable>'

我尝试用Google搜索,但确实找不到关于这两个警告之间的区别的任何有用的线索或博客。

I tried to google but I did not find any helpful thread or blog about what is the difference between these two warnings.

带有一些示例代码片段的示例将为我提供帮助,或者如果要复制某些现有线程,请随时参考。

Example with some sample code snippet will do for me or if am duplicating some existing thread please feel free to refer.

推荐答案

我认为两者之间的差别有些微妙,但这是代码段以及编译器输出所显示的一些差异:

I think the difference is kind of subtle but here is the code snippet along with the compiler output that demonstrates some differences:

#include <iostream>

static const char * hello = "Hello";

void foo() {
    int i;
     std::cout << "foo" << std::endl;
}
...
argenet@Martell ~ % g++ /tmp/def_not_used.cpp -Wall
/tmp/def_not_used.cpp: In function ‘void foo()’:
/tmp/def_not_used.cpp:6:9: warning: unused variable ‘i’ [-Wunused-variable]
     int i;
         ^
/tmp/def_not_used.cpp: At global scope:
/tmp/def_not_used.cpp:3:21: warning: ‘hello’ defined but not used [-Wunused-variable]
 static const char * hello = "Hello";

因此这里从不使用局部变量,因此编译器可以在生成代码时简单地忽略它它会发出未使用的变量警告。

So here the local variable is never used, therefore the compiler may simply omit it while generating the code and it emits an "unused variable" warning.

同时,不能轻易忽略静态C样式文字,因为它可用于更广泛的范围(整个.cpp文件)。
但是,此模块中的任何代码均未引用它,因此编译器会警告它,例如已定义但未使用。

At the same time, the static C-style literal cannot be omitted that easily as it is available for a wider scope (the whole .cpp file). However, it is not referenced by any code in this module so the compiler warns about it like "defined but not used".

这篇关于gcc警告:已定义但未使用与未使用的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆