如何使用extern关键字正确初始化struct[int]
How to initialize a struct[int] correctly with extern keyword
这是我的代码:
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
文件中是一种很好的做法。
- 为什么在全局范围内使用"extern int a"似乎不行?
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- int(c) 和 c-'0' 之间的区别。C++
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- C++ 在"struct std::iterator_traits"中没有名为"value_type"的类型<int>
- 如何将int数组分配给linkedlist struct
- 从数组列表中的字符串迭代器获取 int dat<struct>
- std::int 和 struct 内存不足的映射 (std::Bad_alloc) c++
- 如何从采用 int 和 struct 类型的指针的函数中取消引用指针返回的地址?
- 在向量上找到第一对元素 (int) 并得到第二对元素 (struct)
- 从int到struct的强制转换出现问题
- insert(std::map<int,struct>) 分段错误(核心转储)
- std::map<struct, int> 我需要析构函数吗?
- Is struct A { int a[2] = {1, 2}; }; legal as per C++11?
- 'struct std::pair<int, int>'没有名为'serialize'的成员
- struct和int之间clang中的重新定义不一致
- 如何使用extern关键字正确初始化struct[int]