Error: Unresolved external symbol error in C++

Error: Unresolved external symbol error in C++

编译问题是由全局变量[All_Sockets]引起的,这里是最小的例子

main.cpp

#include <winsock2.h>
#include <windows.h>
#include <vector>
#include "global.h"


int main() {

    std::vector<SOCKET> All_Sockets(10, INVALID_SOCKET);    // definition of global var

    getchar();
    return 1;
}

global.h

#pragma once
#include <vector>
#include <Windows.h>

extern std::vector<SOCKET> All_Sockets;      // declaration of global variable

file1.cpp

#include "global.h"
#include <windows.h>

void ftn1(){
    int i = 2;
    SOCKET Client_socket = All_Sockets[i];      // usage of global var
}

我正在 visual studio 构建这个项目,但出现以下链接错误

1>file1.obj : error LNK2001: unresolved external symbol "class std::vector<unsigned int,class std::allocator<unsigned int> > All_Sockets"

您必须将 All_Sockets 定义为全局变量。当前,All_Sockets 被定义为局部变量,因此 All_Sockets 必须定义在 main 函数之上。

std::vector<SOCKET> All_Sockets(10, INVALID_SOCKET);    // definition of global var

int main() {
    getchar();
    return 1;
}