Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 584
wrongusername Avatar asked Apr 28 '10 20:04

wrongusername


People also ask

Can you define a struct in a header file?

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.

How do you declare a struct in C?

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.

Which header file is used for structure in C?

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.

Where should I define struct in C?

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.


1 Answers

Try this new source :

student.h

#include <iostream>  struct Student {     std::string lastName;     std::string firstName; }; 

student.cpp

#include "student.h"  struct Student student; 
like image 117
Zai Avatar answered Sep 20 '22 15:09

Zai