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() from 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.cppaccessingcolors, so there is no reason to have theexternon its definition.If other files are going to have access to this global data, then declare in
colors.hthat there exists acolorsdata structure:Then in your
color.cppdrop theexternand initialize it as you’re doing. Theexterntells the compiler that the variable is declared (and possibly initialized) somewhere else.If you do access
colorsfrom another file outside ofcolor.cpp, thesizeof colorswon’t work, so you’ll have to signal its size in some other way. Either define the number of colorsOr you can put in a marker in the last slot (e.g.
-1or 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.cto access / manipulate the colors structure so that you’re free to change or update its implementation without affecting the rest of your code base.