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.
Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time. This construct is commonly known as a wrapper #ifndef.
If you declare variables in a . H file, then that is the same as declaring them in your . C file, outside the functions, so as global variables.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
The Header file isn't very smart, it just tells the pre-processor to take the whole header and put it instead of the include line.
if you do that, 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;
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