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?
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.
The general syntax for a struct declaration in C is: struct tag_name { type member1; type member2; /* declare as many members as desired, but the entire structure size must be known to the compiler. */ }; Here tag_name is optional in some contexts.
You request to use a header file in your program by including it with the C preprocessing directive #include, like you have seen inclusion of stdio. h header file, which comes along with your compiler.
If the struct definition is needed from multiple . c files then it should go in the header, otherwise it doesn't have to. @M.M It is only needed in one . c file.
Try this new source :
#include <iostream> struct Student { std::string lastName; std::string firstName; };
#include "student.h" struct Student student;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With