This question already has an answer here:
- What should go into an .h file? 12 answers
I'm trying to create a simple program that takes input from the user in C++ using good programming practices. It consists of Input.hpp, Input.cpp and main.cpp. I keep getting a multiple definition error even though I am using ifndef to prevent that.
Input.hpp
#ifndef Input_HPP
#define Input_HPP
#include <string>
#include <vector>
using namespace std;
vector<string> Get_Input();
vector<string> input_array;
string starting_position;
int input_number;
#endif
Input.cpp
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include "Input.hpp"
using namespace std;
vector<string> Get_Input()
{
cin>>starting_position;
cin>>input_number;
for (int i = 0; i < input_number; i++)
{
cin>>input_array[i];
}
cout<<"Done";
return input_array;
}
main.cpp
#include "Input.hpp"
#include <iostream>
using namespace std;
int main()
{
Get_Input();
return 0;
}
When I remove the variable declarations from the header file and put them in the cpp file but keep the function declaration in the header file the program builds without errors. It is my understanding that variables and functions can be declared in header files. Can someone please explain to me what I am missing?
Thank you.
Header file is not so smart, it just tell the pre-processor to take the whole header and put it instead of the include line.
if you do so you can see the variable is declared twice.
To solve the issue, you should declare the variables in one of your cpp files and use extern
in the headers.
like in input.cpp:
int input_number;
and in input.hpp:
extern int input_number;
The include guard only prevent copying the included file if it was already copied which is working correctly in your code and the compiler can compile the code successfully. Now what you getting is a linker error, after your compiler has generated the object files for Input.cpp
and main.cpp
it will find two symbols -variables- with the same name and will start to complain which one should I use?
So to sum up when you define a variable in a header file add the extern
keyword to keep the linker happy.
来源:https://stackoverflow.com/questions/38942013/declaring-variables-in-header-files-c