Hi, I'm new to C++ and I'm having trouble with this dang linker error. The full error is as follows:

Error 4 error LNK2001: unresolved external symbol "public: static class std::list<class Node,class std::allocator<class Node> > NodeManager::node_list" (?node_list@NodeManager@@2V?$list@VNode@@V?$allocator@VNode@@@std@@@std@@A) Nodes.obj

Error 5 fatal error LNK1120: 1 unresolved externals

From this error, I have deduced that the problem is with NodeManager::node_list. After doing a little researching, I have found that LNK2001 refers to an undefined object, right? I do define node_list as a static member of NodeManager, so I'm not quite sure what's wrong.

Here's some code (I cut it short for brevity's sake):

Node.h

#ifndef NODES_H
#define NODES_H

#include <vector>
#include <list>

class Node {
public:
	std::vector<int> children;

	Node(int num, float x, float y, float z) {
		num_ = num;
		x_ = x;
		y_ = y;
		z_ = z;
	}

private:
	int num_;
	float x_;
	float y_;
	float z_;
};

class NodeManager {
public:
	static std::list<Node> node_list;
};

void generateNodes();

#endif

Node.cpp

#include "Nodes.h"

#include <list>

void generateNodes() {
	Node n1(1, 346.0, 26.5, -470.0);
	n1.children.push_back(2);
	n1.children.push_back(4);
	n1.children.push_back(5);
	NodeManager::node_list.push_back(n1);

	// defining more nodes
}

The only reason I created a NodeManager class is because I need a list to keep track of my node list, and I was told that you cannot create, for example, a list of Node's within the Node definition. Is this correct?

Any ideas? Also, feel free to provide constructive criticism.

Thanks in advance.

Recommended Answers

All 4 Replies

static class objects also have to be declared globally in a *.cpp file

// Node.cpp
#include "Nodes.h"

#include <list>

// declare the static object globally
std::list<Node> NodeManager::node_list;

void generateNodes() {
	Node n1(1, 346.0, 26.5, -470.0);
	n1.children.push_back(2);
	n1.children.push_back(4);
	n1.children.push_back(5);
	NodeManager::node_list.push_back(n1);

	// defining more nodes
}

Wow, thanks for the quick reply. And thanks, that got rid of my errors.

However, is it okay to declare a global list like that if many other files are going to be #include'ing Node.h? Wouldn't that reset its value? That's the reason I was originally trying to do a static list.

You declare it globally in one, and only one *.cpp file. Other *.cpp files that use that header do not have to do that.

Gotcha. Okay, thanks. That definitely solves my problem.

Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.