为队列创建C 全局变量

Creating c++ global variable for a queue

本文关键字:全局变量 创建 队列      更新时间:2023-10-16

注意:此问题在另一个帖子中解决。该职位的链接包括在底部。

我正在使用Visual Studio 2017 Community Edition。我有一个队列,我想成为一个全局变量。

我的主要例程看起来像:

#include "TestClass.h"
using namespace std;
extern queue<Message*> g_incoming;
int main()
{
    PFRHelloMessage* msg1 = new PFRHelloMessage( 0, 1, 2, 30, 40, 1500, 45, 17);
    g_incoming.push(msg1);
    DropLinkMessage* msg2 = new DropLinkMessage( 1, 3, 4);
    g_incoming.push(msg2);
    AddLinkMessage* msg3 = new AddLinkMessage( 2, 5, 6);
    g_incoming.push(msg3);
    //while (!g_incoming.empty())
    //{
    //  Message* m = g_incoming.front();
    //  g_incoming.pop();
    //  cout << m->getType() << endl;
    //}
    TestClass* tc = new TestClass();
    tc->dump();
    return 0;

TestClass看起来像这样:

#include "TestClass.h"
#include <queue>
#include "Message.h"
extern queue<Message*> g_incoming;
void dump()
{
    cout << "start: externally accessed" << endl;
    //while (!g_incoming.empty())
    //{
    //  Message* m = g_incoming.front();
    //  g_incoming.pop();
    //  cout << m->getType() << endl;
    //}
    cout << "end: externally accessed" << endl;
}

我会告诉我的错误,我有两个未解决的外部变量。(当然,这不是真正的程序。我显然在这里不需要外部变量。我需要弄清楚它如何适用于真实程序。(

解决方案:这个问题的每个评论都提供了一些有用的信息;然而,我发现这是一个重复的问题,并且在此处是完整示例答案的链接:何时在C 中使用外部我已经使用自己的课程实现了这一点,并且可以正常工作。我不确定为什么我昨天没有看到(或也许没有注意到(。

我想这是一个链接器问题。只需将定义放入.cpp文件(官方外部(中:

queue<Message*> g_incoming;