views:

637

answers:

2

How do I put a struct in a separate file? I can do it with functions by putting the function prototype in a header file e.g. file.h and the function body in a file like file.cpp and then using the include directive #include "file.h" in the source file with main. Can anybody give a simple example of doing the same thing with a structure like the one below? I'm using dev-c++.

struct person{
  string name;
  double age;
  bool sex;
};
+2  A: 

Just declare

struct person;

It is called class forward declaration. In C++, structs are classes with all members public by default.

Stefano Borini
+2  A: 

If you're talking about a struct declaration:

person.h :

#ifndef PERSON_H_
#define PERSON_H_
struct person{ 
  string name; 
  double age; 
  bool sex; 
};
#endif

Then you just include person.h in the .cpp files where you need that struct.

If you're talking about a (global) variable of the struct:

person.h :

#ifndef PERSON_H_
#define PERSON_H_
struct person{ 
  string name; 
  double age; 
  bool sex; 
};
extern struct Person some_person;
#endif

And in one of your .cpp files you need this line, at global scope,that holds the definition for 'some_person'

struct Person some_person;

Now every .cpp file that needs to access the global 'some_person' variable can include the person.h file.

nos
Your first bit of code is a struct definition, not just a struct declaration.
Steve Jessop