Can you define structs in header files?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KioKrofov
    New Member
    • Jun 2008
    • 7

    Can you define structs in header files?

    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.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    .h:
    Code:
    struct myData
    {
    int dataCodeNum;
    char* dataName;
    }
    
    extern myData arrayOfData1[];
    .c:
    Code:
    myData arrayOfData1[] = { {0,"aa"}, {1,"bb"} };

    Comment

    • KioKrofov
      New Member
      • Jun 2008
      • 7

      #3
      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"

      Comment

      • oler1s
        Recognized Expert Contributor
        • Aug 2007
        • 671

        #4
        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).

        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.

        Comment

        • KioKrofov
          New Member
          • Jun 2008
          • 7

          #5
          Oh okay! Thanks much

          Comment

          Working...