如何使用extern关键字正确初始化struct[int]

How to initialize a struct[int] correctly with extern keyword

本文关键字:struct int 初始化 何使用 extern 关键字      更新时间:2023-10-16

这是我的代码:

main.cpp

#include "color.h"
int main ( int argc , char **argv ) 
{
    Highlight h;
    return 0;
}

color.h

#ifndef HIGH_H
#define HIGH_H
#include <iostream>
using namespace std;
struct colorPattern_t
{
    int c1 , c2;
    colorPattern_t ( int a , int b )
    {
        c1 = a; c2 = b;
        cout << "colorPattern_t() with " << c1 << " , " << c2 << endl;
    }
    void say()
    {
        cout << "say() from colorPattern_t" << endl;
    };
};
class Highlight
{
    public:
    Highlight ();
};
#endif

现在颜色.cpp

#include "color.h"
extern colorPattern_t colors[2] = 
{
    {
        1,
        2
    } ,
    {
        4,
        5
    }
};
Highlight::Highlight()
{
    for ( int i = 0 ; i < sizeof(colors) / sizeof(colorPattern_t) ; i ++ )
    {
        colors[i].say();
    }
};

使用编译时

g++主.cpp颜色.cpp-o主

我看到了:

color.cpp:3:31:警告:"colors"已初始化并声明为"extern"
color.cpp:13:1:警告:扩展初始值设定项列表仅在-std=c++0x或-std=gnu++0x时可用
color.cpp:13:1:警告:扩展初始值设定项列表仅适用于-std=c++0x或-std=gnu++0x

我的colorPattern_t{}初始化方法有什么建议吗?我希望将它们安装在我的代码中,而不使用-std=c++0x来修复症状。

在您的示例中,我没有看到color.cpp之外的任何东西访问colors,因此没有理由在其定义中包含extern

如果其他文件将访问此全局数据,则在colors.h中声明存在colors数据结构:

extern colorPatterns_t colors[];

然后在您的color.cpp中删除extern,并按照您的操作对其进行初始化。extern告诉编译器变量是在其他地方声明的(并且可能是初始化的)。

如果您确实从color.cpp之外的另一个文件访问colors,则sizeof colors将不起作用,因此您必须以其他方式通知其大小。要么定义的颜色数量

 /* in colors.h */
 #define N_COLORS 2
 extern colorPatterns_t colors[];
 /* in color.cpp */
 colorPatterns_t colors[N_COLORS] = { ...

或者,您可以在最后一个插槽中放入一个标记(例如-1或其他明显的非法值)。

当然,全局变量通常是邪恶的,您应该在color.c中提供一组例程/方法来访问/操作颜色结构,这样您就可以自由地更改或更新其实现,而不会影响代码库的其余部分。

只需删除extern关键字。非static全局变量本质上是extern。它应该可以正常工作。

编辑:如果color.h包含在多个文件中,则可能会导致链接器错误。因此,将数组定义保留在.cpp文件中并将extern <array>语法放在.h文件中是一种很好的做法。