在h文件中声明的c ++静态数组给出警告“defined but not used” [英] c++ static array declared in h file gives warning 'defined but not used'

查看:5271
本文介绍了在h文件中声明的c ++静态数组给出警告“defined but not used”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇以下。我有一个简单的C数组声明在一个头文件像这样:

I'm curious about the following. I have a simple C array declared in a header file like this:

static int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17};

它给了我一些警告:

: 'userCardsIndexes' defined but not used

我包括这个文件到我的cpp文件,并使用这个变量。我不明白的第二件事是当我添加 const 说明符,像这样:

despite i include this file into my cpp files and use this variable. The second thing that i don't understand about it is when i add const specifier like this:

static const int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17};

警告消失!任何人都可以给我一个解释,为什么我得到这些警告,为什么 const 删除它们?

the warnings disappear! Can anyone give me an explanation why i get these warnings and why const removes them?

推荐答案

简单的答案是:你在头部定义一个数组,而不只是声明它。不是很好。如果你需要数组可访问的每当你包括头,应该有一个声明在头如下:

The short answer is: you're defining an array in a header, not just declaring it. This is not good. If you need the array accessible whenever you include the header, there should be a declaration in the header as such:

extern int userCardsIndexes[INITIAL_CARDS_NUMBER];

然后,在只有一个源文件中,定义数组:

And then, in only one source file, define the array as such:

int userCardsIndexes[INITIAL_CARDS_NUMBER] = {0, 1, 8, 9, 16, 17};






至于长的答案: 关于头文件; #include 指令只是将头文件的全部内容复制到源文件中。所以基本上,你得到的是一个新的静态数组 userCardsIndexes 在每个源文件中定义;如果不使用此数组,则会得到未使用的变量警告。前面的 const 很可能会抑制警告,只是因为编译器没有配置为警告在 const 未使用的变量。例如:使用GCC,请查看-Wunused-variable的文档:


As to the long answer: there's nothing "magical" about a header file; the #include directive just basically copies the entire contents of the header file into your source file. So essentially, what you're getting is a new static array userCardsIndexes defined in every source file; if this array isn't used, you get the "unused variable" warning. Prepending the const is likely suppressing the warning just because the compiler isn't configured to warn on const unused variables. For example: using GCC, look at the documentation for "-Wunused-variable":

http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

这篇关于在h文件中声明的c ++静态数组给出警告“defined but not used”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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