Declaring variables in header files C++ [duplicate]

扶醉桌前 提交于 2019-12-06 18:00:43

问题


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.


回答1:


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;



回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!