1

So I tried to define a struct in its own .cpp file (for organization or whatever) and I forward declared it in a header, included the header in the .cpp file, then included the header in main.cpp and tried to create a vector of the struct, and it did not work. However I then took the definition of the struct and put it into main.cpp and it did work. Is this just a quirk of structs that I was unaware of, that they need to be defined in the file that they are used (for some reason)? Here was the code:

//people.h
struct People;

//people.cpp
#include people.h
struct People
{
std::string name;
int age;
};

//main.cpp
#include"people.h"
#include<vector>
std::vector<People> list;
Fuddlebutts
  • 61
  • 1
  • 5

2 Answers2

5

When compiling main.cpp, the compiler can only see the contents files that have been #included. This means that it can only see struct People; which is a forward declaration, not a full definition. The declaration std::vector<People> needs to know how big a People structure actually is, so the compiler need to see the whole definition.

You will need to put the entire struct People { ... }; definition into people.h. (You could copy and paste the definition into main.cpp, but having multiple definitions of a structure is a really bad idea because it's hard to keep them all in sync.)

Forward declarations of structures are useful if you only need to use that structure in the context of a pointer or reference to it.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Ah, so when you forward declare functions in header files, define them in another .cpp file (with header included) and include them in main.cpp it works differently? (Basically like the code in my question but with a function instead of a struct) – Fuddlebutts Mar 31 '12 at 22:20
  • Right, when you *call* a function, the compiler doesn't need to know what is *inside* the function. The linker just hooks them up after the the compilation step. (However, when you get to C++ template functions, you generally have to put *those* in the header file.) – Greg Hewgill Mar 31 '12 at 22:21
0

You have to define structs and classes in *.H files and include the headers in the desired *.CPP files. Structure defined in the *.CPP is file-local.

iehrlich
  • 3,572
  • 4
  • 34
  • 43