定义全局数组 [英] Defining global array

查看:148
本文介绍了定义全局数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在头文件中有以下静态数组:

  static MyStruct_t MyStructArray [] = {
.. ....
......
......
}

但是gcc发出警告:

 警告:`MyStructArray' b  

处理这种情况的正确方法是什么?



UPD:



将数组定义为const:

  const MyStruct_t MyStructArray [] = {
......

修复thwe情况。因此,在头文件中声明数组static是什么,因此头文件中首选的extern或const是什么?

解决方案

每个编译单元(即预处理的.cpp文件)获得自己的数组副本 - 几乎肯定不是你想要的,以及你得到已定义但未使用错误的确定原因。


相反,你可能想要在你的头文件中:

  extern MyStruct_t * MyStructArray; 

...然后在1个.cpp文件中:

  MyStruct_t MyStructArray [] = {...}; 


I have the following static array in header file:

static MyStruct_t MyStructArray[] = {
    ......
    ......
    ......     
}

But gcc issues a warning:

warning: `MyStructArray' defined but not used

What is the correct way to handle the situation?

UPD:

Defining the array as const:

const MyStruct_t MyStructArray[] = {
    ......

fixes thwe situation. So what is the preferred way extern or const in header?

解决方案

Because you've declared the array static in a header file, each compilation unit (i.e. preprocessed .cpp file) gets its own copy of the array--almost certainly not what you intended, and the sure reason that you get the "defined but not used" error.

Instead, you probably want this in your header file:

extern MyStruct_t *MyStructArray;

...and then in exactly 1 .cpp file:

MyStruct_t MyStructArray[] = { ...};

这篇关于定义全局数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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