在头文件C ++中声明变量 [英] Declaring variables in header files C++

查看:129
本文介绍了在头文件C ++中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的程序,该程序使用良好的编程习惯来接收C ++中用户的输入.它由Input.hpp,Input.cpp和main.cpp组成.即使我正在使用ifndef来防止这种情况,我仍然收到多定义错误.

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

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

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;
}

当我从头文件中删除变量声明并将其放在cpp文件中,但将函数声明保留在头文件中时,程序将构建而没有错误.据我了解,可以在头文件中声明变量和函数.有人可以向我解释我所缺少的吗?

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?

谢谢.

推荐答案

Header文件不是很聪明,它只是告诉预处理器获取整个标头并放入它,而不是包含行.

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.

要解决此问题,应在一个cpp文件中声明变量,并在标题中使用extern.

To solve the issue, you should declare the variables in one of your cpp files and use extern in the headers.

就像在input.cpp中一样:

like in input.cpp:

int input_number;

以及在input.hpp中:

and in input.hpp:

extern int input_number;

这篇关于在头文件C ++中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆