C++, how to declare a struct in a header file

wrongusername picture wrongusername · Apr 28, 2010 · Viewed 127.9k times · Source

I've been trying to include a structure called "student" in a student.h file, but I'm not quite sure how to do it.

My student.h file code consists of entirely:

#include<string>
using namespace std;

struct Student;

while the student.cpp file consists of entirely:

#include<string>
using namespace std;

struct Student {
    string lastName, firstName;
    //long list of other strings... just strings though
};

Unfortunately, files that use #include "student.h" come up with numerous errors like

error C2027: use of undefined type 'Student'

error C2079: 'newStudent' uses undefined struct 'Student'  (where newStudent is a function with a `Student` parameter)

error C2228: left of '.lastName' must have class/struct/union 

It appears the compiler (VC++) does not recognize struct Student from "student.h"?

How can I declare struct Student in "student.h" so that I can just #include "student.h" and start using the struct?

Answer

Zai picture Zai · Apr 28, 2010

Try this new source :

student.h

#include <iostream>

struct Student {
    std::string lastName;
    std::string firstName;
};

student.cpp

#include "student.h"

struct Student student;