这是我的代码:
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
文件中是一种很好的做法。