LNK1169 找到一个或多个多重定义的符号。我知道这可以被认为是重复的,但我找不到任何解决我问题的方法

LNK1169 one or more multiply defined symbols found. I know this could be considered a duplicate but I could not find anything that solved my problem

我有一个老师需要的头文件。我正在使用全局变量,因此我可以将值从一个函数移动到另一个函数。查找问题,有人建议使用命名空间。那没有用。此外,我像其他人推荐的那样添加了一些警卫,但这也无济于事。 我有多个文件和 extern in header 的普遍接受的解决方案,然后 .cpp 中的声明由于某种原因对我不起作用。 Global variables in header file

Methods.h


#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

WSCreate.cpp

中变量的一种用法
// 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;
        }
}

WSRead.cpp(这个全局变量的另一种用法)

 for (int i = 0; i != number_of_employees; i++)
    {
        cout << endl;
        employees >> printing;
        cout << printing << " ";
        employees >> printing;
        cout << printing << "\t  ";
        employees >> printing;
        cout << printing << "\t\t";
        employees >> printing;
        cout << printing << "\t\t";
        employees >> printing;
        cout << printing;
        cout << endl;
    }

再次抱歉,如果这是一个重复的问题,但我找不到问题的解决方案。

提前致谢。

如果您需要更多代码,请告诉我。

导出全局变量时,您希望在 c++ 文件中定义它们,以便编译器只编译一次。

目前,从 .h 文件中包含它会将它添加到您的所有 .obj 文件(由编译器构建),并且链接器在尝试构建您的 .exe 时不喜欢在多个位置存在的相同变量或图书馆。

您需要做的是在 header 文件中将变量声明为“extern”,并将其声明(相同)添加到适当的 .cpp 文件中。

在 header 中:

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 或更高版本,你可以检查你的项目属性中是否有 /std:c++17 或 /std:c++latest 标志,在 visual studio 在

之下

项目 -> 属性 -> 配置属性 -> 常规 -> C++ 语言标准。

为了完成,对于 GNU 或 GNU-inspired 编译器,您需要标志 -std=c++17。

晚上好,