-1

Note: This problem is solved in another post. The link to that post is included at the bottom.

I'm using Visual Studio 2017 community edition. I have a queue I want to be a global variable.

My main routine looks like this:

#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 looks like this:

#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;
}

The errors I get tell me that I have two unresolved external variables. (Of course this is not the real program. I obviously don't need an external variable here. I need to figure out how this works for the real program.)

Solution: Each of the comments to this question offers some useful information; however, I've discovered this is a duplicate question and a link to complete example answer is here: When to use extern in C++ I've implemented this using my own classes and it works. I'm not sure why I didn't see (or perhaps didn't notice) that result yesterday.

elbillaf
  • 1,952
  • 10
  • 37
  • 73
  • please post the error message verbatim instead of paraphrasing it in your own words. And please provide a [mcve] (instead of leaving a note that this isnt the real code) – 463035818_is_not_an_ai Apr 23 '18 at 18:46
  • 1
    There is nothing particular to queue here. You have 2 declarations for a global variable (promising that you have created it somewhere), but no definition (actually creating it). You need to add exactly one definition in only one of your .cpp files. – Avi Berger Apr 23 '18 at 18:52
  • As @Frank suggests, removing extern from only one of your .cpp files will do it. I would tend to move the declarations to an appropriate .h file and have a definition in the most appropriate .cpp file. – Avi Berger Apr 23 '18 at 18:57
  • What I mean by saying "it's not the real" program is that the example is a toy. It is incomplete, but sufficient for diagnosis, as is evidenced by the fact that several people gave useful information. – elbillaf Apr 24 '18 at 11:55

1 Answers1

1

I suppose it's a linker problem. Simply put the definition into a .cpp file (ommitting extern):

queue<Message*> g_incoming;
kiloalphaindia
  • 561
  • 3
  • 7