问题描述
我有一个我的老师需要的头文件。我正在使用全局变量,因此我可以将值从一个函数移动到另一个函数。查找问题,有人推荐使用命名空间。那没有用。此外,我像其他人推荐的那样添加了一些守卫,但这也无济于事。 我有多个文件,头文件中普遍接受的 extern 解决方案,然后 .cpp 中的声明由于某种原因对我不起作用。 Global variables in header file
方法.h
New ServiceBusClient(connStr)
WSCreate.cpp 中变量的一种用法
#pragma once
#define METHODS_H
#include <cfguard.h>
#ifdef METHODS_H
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
// declaring global variables
namespace global_variables
{
int number_of_employees;
}
#endif
// for loop to make sure amount of employees is integer
int count = 0;
int triggered = 0;
while (true){
cout << "Enter the number of employees you would like to enter\n";
string employees_in_string_format;
getline (cin,employees_in_string_format);
for (int i = 0; i < employees_in_string_format.length(); ++i)
{
triggered = 0;
if (isdigit(employees_in_string_format[i]) == false)
{
count = 1;
triggered = 1;
}
else
{
count = 0;
}
}
if (triggered == 1)
{
cout << "One of your inputs for the amount of employees you have is not a positive integer. Please enter \n positive integers\n";
}
else if (triggered == 0)
{
cout << "Your inputs are validated!\n";
number_of_employees = stoi(employees_in_string_format);
break;
}
}
再次抱歉,如果这是一个重复的问题,但我找不到我的问题的解决方案。
提前致谢。
如果您需要更多代码,请告诉我。
解决方法
在导出全局变量时,您希望在 C++ 文件中定义它们,以便编译器只编译一次。
目前,从 .h 文件中包含它会将其添加到您的所有 .obj 文件(由编译器构建)中,并且链接器在尝试构建您的 .exe 或库时不喜欢在多个位置存在的相同变量.
您需要做的是在头文件中将变量声明为“extern”,并将其声明(相同)添加到适当的 .cpp 文件中。
在标题中:
extern int number_of_employee;
在 .cpp 中
int number_of_employee;
此外,如果您想在 .cpp 文件中使用全局变量,但又不希望它被任何声明的外部文件修改
extern int your_variable_name;
您应该将其定义为“静态”,这意味着它不会被链接器看到,并且对于它在其中定义的 .obj 来说是“私有的”。
编辑(像这样):
static int your_variable_name;
编辑(根据@dxiv 的评论):
自 c++17 起,一种可能的首选方法(因为它会减少膨胀)是将变量声明为内联变量 - 这告诉链接器它可以有多个声明,如果是变量,则所有声明都应合并为最终二进制文件中的单个二进制数据位。
inline int number_of_employee;
要确保您使用 msvc++ 启用了 c++17 或更高版本,您可以在 Visual Studio 下检查您的项目属性中是否有 /std:c++17 或 /std:c++latest 标志
项目 -> 属性 -> 配置属性 -> 常规 -> C++ 语言标准。
为了完成起见,对于 GNU 或受 GNU 启发的编译器,您需要标志 -std=c++17。
祝你有个愉快的夜晚