C++, how to declare a struct in a header file
Try this new source :
student.h
#include <iostream>
struct Student {
std::string lastName;
std::string firstName;
};
student.cpp
#include "student.h"
struct Student student;
Your student.h file only forward declares a struct named "Student", it does not define one. This is sufficient if you only refer to it through reference or pointer. However, as soon as you try to use it (including creating one) you will need the full definition of the structure.
In short, move your struct Student { ... }; into the .h file and use the .cpp file for implementation of member functions (which it has none so you don't need a .cpp file).
C++, how to declare a struct in a header file:
Put this in a file called main.cpp:
#include <cstdlib>
#include <iostream>
#include "student.h"
using namespace std; //Watchout for clashes between std and other libraries
int main(int argc, char** argv) {
struct Student s1;
s1.firstName = "fred"; s1.lastName = "flintstone";
cout << s1.firstName << " " << s1.lastName << endl;
return 0;
}
put this in a file named student.h
#ifndef STUDENT_H
#define STUDENT_H
#include<string>
struct Student {
std::string lastName, firstName;
};
#endif
Compile it and run it, it should produce this output:
s1.firstName = "fred";
Protip:
You should not place a using namespace std;
directive in the C++ header file because you may cause silent name clashes between different libraries. To remedy this, use the fully qualified name: std::string foobarstring;
instead of including the std namespace with string foobarstring;
.
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.