How to initialize a struct[int] correctly with extern keyword
Here's my code:
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() fr开发者_开发技巧om colorPattern_t" << endl;
};
};
class Highlight
{
public:
Highlight ();
};
#endif
Now color.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();
}
};
When compiling with:
g++ main.cpp color.cpp -o main
I see:
color.cpp:3:31: warning: ‘colors’ initialized and declared ‘extern’
color.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x color.cpp:13:1: warning: extended initializer lists only available with -std=c++0x or - std=gnu++0x
I there any suggestion for my colorPattern_t{}
initialization method? I wanted them to be mounted in my code without using -std=c++0x
to fix the symptom.
In your example, I don't see anything outside of color.cpp
accessing colors
, so there is no reason to have the extern
on its definition.
If other files are going to have access to this global data, then declare in colors.h
that there exists a colors
data structure:
extern colorPatterns_t colors[];
Then in your color.cpp
drop the extern
and initialize it as you're doing. The extern
tells the compiler that the variable is declared (and possibly initialized) somewhere else.
If you do access colors
from another file outside of color.cpp
, the sizeof colors
won't work, so you'll have to signal its size in some other way. Either define the number of colors
/* in colors.h */
#define N_COLORS 2
extern colorPatterns_t colors[];
/* in color.cpp */
colorPatterns_t colors[N_COLORS] = { ...
Or you can put in a marker in the last slot (e.g. -1
or some other obvious illegal value).
Of course, global variables are in general evil and you should just supply a set of routines/methods in color.c
to access / manipulate the colors structure so that you're free to change or update its implementation without affecting the rest of your code base.
Just remove the extern
keyword. Non-static
globals are extern
by nature. It should work fine.
Edit: if color.h
is included in multiple files, then it might give linker error. So it's a good practice to keep the array definition in .cpp
file and put the extern <array>
syntax in .h
file.
精彩评论