在头文件C++中声明变量

Kar*_*ala 14 c++ header-files

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

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
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "Input.hpp"
#include <iostream>
using namespace std;

int main()
{

    Get_Input();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我从头文件中删除变量声明并将它们放在cpp文件中但保留头文件中的函数声明时,程序构建没有错误.我的理解是变量和函数可以在头文件中声明.有人可以向我解释我错过了什么吗?

谢谢.

SHR*_*SHR 17

头文件不是那么聪明,它只是告诉预处理器取整个头并把它放在包含线上.

如果你这样做,你可以看到变量被声明两次.

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

比如input.cpp:

int input_number;
Run Code Online (Sandbox Code Playgroud)

在input.hpp中:

extern int input_number;
Run Code Online (Sandbox Code Playgroud)

  • 这就是变量的前向声明的完成方式。有关 extern 关键字的更多信息 [6.7 — 外部链接和变量前向声明](https://www.learncpp.com/cpp-tutorial/external-linkage-and-variable-forward-declarations/) (2认同)

Moh*_*nis 6

如果包含的文件已经在您的代码中正常工作并且编译器可以成功编译代码,则包含保护只会阻止复制包含的文件。现在你得到的是一个链接器错误,在你的编译器生成了目标文件之后Input.cppmain.cpp它会找到两个同名的符号 - 变量 - 并开始抱怨我应该使用哪个?

总而言之,当您在头文件中定义变量时,请添加extern关键字以使链接器满意。