Connecting Tech Pros Worldwide Forums | Help | Site Map

Can you define structs in header files?

Newbie
 
Join Date: Jun 2008
Posts: 7
#1: Jul 18 '08
Currently I have (a much bigger version of) the code below in my main cpp file:

struct myData
{
int dataCodeNum;
char* dataName;
}

myData arrayOfData1[]={
{ 1, "Data 1.1" },
{ 2, "Data 1.2" },
{ 3, "Data 1.3" },
};

myData arrayOfData2[]={
{ 1, "Data 2.1" },
{ 2, "Data 2.2" },
{ 3, "Data 2.3" },
};

I need the struct definition and the arrays of structs to be accessible to many functions and classes throughout my program, but I was hoping to get them out of the main cpp interface file.

I was thinking about plopping the whole thing in a header file and then #include-ing that file to all other files that would use these arrays of structs, but that just seems wrong to have objects in the header file... I mean, when you have a class, you only put the class definition in the header file, and your objects get declared in some cpp file...

Thus far everything I have read or looked up has shown how to create structs, but I am having a hard time finding any information about putting these structs (and/or their objects) in separate files.

Thanks.

Needs Regular Fix
 
Join Date: Jul 2008
Posts: 386
#2: Jul 19 '08

re: Can you define structs in header files?


.h:
Expand|Select|Wrap|Line Numbers
  1. struct myData
  2. {
  3. int dataCodeNum;
  4. char* dataName;
  5. }
  6.  
  7. extern myData arrayOfData1[];
  8.  
.c:
Expand|Select|Wrap|Line Numbers
  1. myData arrayOfData1[] = { {0,"aa"}, {1,"bb"} };
  2.  
Newbie
 
Join Date: Jun 2008
Posts: 7
#3: Jul 21 '08

re: Can you define structs in header files?


So then, it is not considered poor programming practice to place implementation (by defining an object of the struct) in a header file?

I thought you were not supposed to declare variables (in this case an object of the struct) in header files because you will get a linking error "already defined in *.obj"
Expert
 
Join Date: Aug 2007
Posts: 674
#4: Jul 21 '08

re: Can you define structs in header files?


Quote:
it is not considered poor programming practice to place implementation (by defining an object of the struct) in a header file?
The array was declared (notice the use of extern).

Quote:
I thought you were not supposed to declare variables
You're not supposed to define something. You can't have multiple definitions of a variable.
Newbie
 
Join Date: Jun 2008
Posts: 7
#5: Jul 21 '08

re: Can you define structs in header files?


Oh okay! Thanks much
Reply