27

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.

Kareem Aboughazala
  • 535
  • 1
  • 6
  • 15

2 Answers2

44

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;
CodeShady
  • 7
  • 4
SHR
  • 7,940
  • 9
  • 38
  • 57
  • 1
    This is how forward declaration of variables is done. More on extern keyword [6.7 — External linkage and variable forward declarations](https://www.learncpp.com/cpp-tutorial/external-linkage-and-variable-forward-declarations/) – Enes Jun 09 '22 at 08:42
8

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.

Mohamed Moanis
  • 477
  • 7
  • 18
  • I'm sorry but, which are the two symbols with the same name? If the include guard prevented copying `input_number` in both files, wouldn't exist only one declaration of that variable? – Hans GD May 08 '23 at 18:07