This question already has answers here:
C++ inlining class methods causes undefined reference
(3 answers)
When should I write the keyword 'inline' for a function/method?
(16 answers)
Closed 2 years ago.
I'm trying to have a class call a function from an inherited class however whenever I do I get an unresolved external error LNK2019. I'm confused to why this is happening as all of the files appear to be properly included, I haven't overridden the function & Visual Studio doesn't complain about it prior to compiling.
I've tried:
Running the replacing the function call with the actual code, this fixes one of the two errors but I still get an unresolved external as the functions in question are calling another function from another class.
Messing around with namespaces, as the inherited class is under a separate namespace I thought that was the problem e.g. Memory::Allocate(...).
Directly calling the class function, so instead of Allocate(...) I tried Memory::GlobalMemoryUser::Allocate(...)
Calling the function using this->...
Relevant code from GlobalMemoryUser.h
#include "MemoryManager"
namespace Memory
{
namespace Internal
{
extern MemoryManager* GlobalMemoryManager;
{
class GlobalMemoryUser
{
public:
// Allocator and deallocator
inline const void* Allocate(size_t, const char* user);
inline const void DeAllocate(void*);
private:
// A pointer to the global memory manager
Internal::MemoryManager* GlobalMemoryManager;
};
}
Relevant code from GlobalMemoryManager.cpp
#include "GlobalMemoryUser.h"
namespace Memory {
const void* GlobalMemoryUser::Allocate(size_t size, const char* user)
{
return GlobalMemoryManager->Allocate(size, user);
}
const void GlobalMemoryUser::DeAllocate(void* p)
{
GlobalMemoryManager->DeAllocate(p);
}
}
Relevant code from System Manager.h
#include "GlobalMemoryUser.h"
namespace ECS
{
class SystemManager : public Memory::GlobalMemoryUser
{
// Constructor and Deconstructor
SystemManager();
~SystemManager();
};
}
Relevant code from SystemManager.cpp
#include "SystemManager.h"
namespace ECS
{
SystemManager::SystemManager()
{
systemAllocator = new Memory::LinearAllocator(ECS_SYSTEM_MEMORYBUFFERSIZE, Allocate(ECS_SYSTEM_MEMORYBUFFERSIZE, "SystemManager"));
}
SystemManager::~SystemManager()
{
for (std::vector<ISystem*>::reverse_iterator it = systemWorkOrder.rbegin(); it != systemWorkOrder.rend(); it++)
{
(*it)->~ISystem();
*it = nullptr;
}
systemWorkOrder.clear();
systemsTable.clear();
DeAllocate((void*)systemAllocator->GetUsedMemoryStart());
delete systemAllocator;
systemAllocator = nullptr;
}
}
The errors in question happen within the constructor and deconstructor for the system manager when trying to call the allocator and deallocator from the GlobalMemoryUser parent class.
Exact Error Message:
LNK2019 unresolved external symbol "public: void const * __cdecl Memory::GlobalMemoryUser::Allocate(unsigned __int64,char const *)" (?Allocate#GlobalMemoryUser#Memory##QEAAPEBX_KPEBD#Z) referenced in function "public: __cdecl ECS::SystemManager::SystemManager(void)" (??0SystemManager#ECS##QEAA#XZ)
Related
This question already has answers here:
Undefined reference to static class member
(9 answers)
Closed 7 years ago.
I tried to make the following singleton class in C++
#pragma once
#include "stdafx.h"
#include <iostream>
class God
{
private:
static God* firstObject;
God()
{
if (firstObject != NULL)
firstObject = this;
}
public:
static God* BuildGod()
{
if (firstObject != NULL)
return firstObject;
else {
God();
return firstObject;
}
}
};
and then use it like so
God* a = God::BuildGod();
Unfortunatley, it won't even compile and it returned the following errors:
LNK2001 unresolved external symbol "private: static class God * God::firstObject" (?firstObject#God##0PAV1#A)
LNK1120 1 unresolved externals
You actually have a worse problem than the build error, because you create a temporary object, and save a pointer to it to be used.
The statement
God();
creates a temporary object, and in the constructor you save a pointer to this temporary object in firstObject which you then return. Using that pointer will then lead to undefined behavior.
One of the usual ways of creating a singleton in C++ would be something like this:
class God
{
public:
static God& get_instance() {
{
static God instance; // This is THE instance
return instance;
}
private:
God() {}
};
A static member of a class has to be defined outside the class, like
class God
{
...
};
God* God::firstObj;
Just beware that having the definition in a header file and including it mamy times calls for trouble.
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 8 years ago.
I've been developing C# and Java (among many other languages) for many years, and I'm just now getting my feet wet in C++. I've buried myself in resources on inheritance and classes, but I just can't seem to figure out how to get rid of this pesky error.
My code:
Entity.h:
#ifndef ENTITY_H
#define ENTITY_H
#include <iostream>
class Entity
{
public:
std::string m_name;
void update(float delta);
Entity();
private:
virtual void step(float delta);
};
#endif
Entity.cpp:
#include "Entity.h"
Entity::Entity()
{
m_name = "Generic Entity";
}
void Entity::update(float delta)
{
step(delta);
}
void Entity::step(float delta) {}
Player.h:
#ifndef PLAYER_H
#define PLAYER_H
#include "Entity.h"
class Player : public Entity
{
public:
Player();
private:
virtual void step(float delta);
virtual void draw() const;
};
#endif
Player.cpp:
#include "Player.h"
Player::Player()
{
m_name = "Player";
}
void Player::step(float delta) {}
void Player::draw() const {}
Main.cpp:
int main()
{
return 0;
}
As you can see, I'm not doing anything with the classes, but I'm getting these errors:
Error 3 error LNK1120: 1 unresolved externals C:\[...]\Debug\ConsoleApplication1.exe ConsoleApplication11
Error 2 error LNK2019: unresolved external symbol "public: __thiscall Entity::Entity(void)" (??0Entity##QAE#XZ) referenced in function "public: __thiscall Player::Player(void)" (??0Player##QAE#XZ) C:\[...]\ConsoleApplication1\Player.obj ConsoleApplication1
UPDATE: The code magically works when I comment out the following code in Player.cpp:
/*Player::Player()
{
m_name = "Player";
}*/
It looks like Entity isn't linked to player. Make sure output shows it compiling and that they are both added to your project
You also need to define a virtual destructor in your base class
Edit:
It doesn't have to compile first, my mistake. In C/C++, program creation is in two steps. First the compiler creates obj files for your cpp files, such as Entity.obj, Player.obj and so on. Then the linker will bundle everything together.
In Player.cpp, you say that you will have a class named Entity at some point, so the compiler finds the definition of that class in the .h file. Player.cpp then gets transformed into executable code in Player.obj but it won't contain the Entity.obj executable code. The compilation step works.
Then the linker will try to parse Player.obj and find Entity.obj that the compiler said will exists. If it doesn't then you get the "undefined reference" error, because the definitions found do not match the actual executable.
The virtual destructor is mandatory. The way inheritance works in C++ is with the virtual table. For each class with inheritance, a virtual table (vtable) is created with the virtual entries. When the linking step is performed, the linker will fill the vtable with the actual function. When the code executes, it checks the vtable for that class then execute that function. This allows you to "override" base methods or use the base method if nothing new is added. The virtual destructor creates the entry in that table for the destructor. If there is no entry for a virtual destructor, then the child class will not have an entry and won't be able to destroy the base class properly, which results in undefined behavior
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
I'm working on own double linked list and everytime after adding object of class DoubleList in Evidence.cpp I get a LNK2019 error: Unresolved external symbol. I will be glad for every advice. Here are my codes:
StudentRecord.h
#pragma once
#include <string>
#include <iostream>
#include <algorithm>
#include "Student.h"
#include "DoubleList.h"
using namespace std;
using namespace SemestralWork;
class StudentRecord{
public:
DoubleList<Student> *List; //declared object (in StudentRecord.cpp is problem with that)
StudentRecord(void);
~StudentRecord(void);
Student &SearchStudent(const string &ID);
void addStudent(const Student &student, Student::Position position = Student::Position::LAST);
Student RemoveStudent(const string &ID);
void WriteAllStudents(void);
void Cancel(void);
};
StudentRecord.cpp (just part)
#include "StdAfx.h"
#include "StudentRecord.h"
using namespace SemestralWork;
StudentRecord::StudentRecord(void)
{
List = new DoubleList<Student>(); // <---- here is first LNK2019 error
}
Student &StudentRecord::SearchStudent(const string &ID){
Student * SearchedStudent;
Student * EmptyStudent = NULL;
//********** down here are next 4 LNK2019 errors. ************
for(DoubleList<Student>::iterator it = List->begin(); it != List->end(); ++it){
if(ID == List->AccessActual().getID()){
SearchedStudent = &List->AccessActual();
return *SearchedStudent;
}
} // 5 unresolved externals
return *EmptyStudent;
}
//...
DoubleList (just constructor)
template<typename T>
DoubleList<T>::DoubleList(void){
NumberOfElements = 0;
First= NULL;
Last= NULL;
Actual= NULL;
}
Student.h
#pragma once
#include <string>
using namespace std;
class Student
{
private:
string firstName, lastName, ID;
public:
Student(string, string, string);
~Student(void);
string getFirstName();
string getLastName();
string getID();
enum Position{ FIRST, LAST, ACTUAL, PREVIOUS, NEXT};
};
EDIT: Error message here:
Error 5 error LNK2019: unresolved external symbol "public: class Student & __thiscall SemestralWork::DoubleList::AccessActual(void)" (?AccessActual#?$DoubleList#VStudent###SemestralWork##QAEAAVStudent##XZ) referenced in function "public: class Student & __thiscall StudentRecord::SearchStudent(class std::basic_string,class std::allocator > const &)" (?SearchStudent#StudentRecord##QAEAAVStudent##ABV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std###Z)
(one of five LNK errors)
So, you have a message. I'll break the message in several lines. The message should be read like this:
LNK2019: unresolved external symbol
"some function or variable that compiler saw nicely declared but the linker can't find the definition of"
(name of the missing symbol as linker sees it)
referenced in function
"some function where the missing function/variable is being used"
(name of the function as linker sees it)
In your case linker needs function DoubleList::AccessActual(void) in namespace SemestralWork. The function is declared somewhere, most likely in DoubleList.h. You probably need to add DoubleList.cpp file to the project. Maybe you forgot to define the function? In that case you have to write it.
Also, you really, really need to remove using namespace lines from header files. Really! Classes that exist in namespaces MUST be declared like this:
namespace SomeNamespace {
class SomeClass
{
void SomeFunction();
...
}
}
And SHOULD be defined like this in source file:
void SomeNamespace::SomeClass::SomeFunction()
{
...
}
In header files all stuff from any other namespaces, including std namespace, SHOULD be used with full name (std::string). In source files you MAY use using namespace std AFTER all #include directives. Some people disagree on this last one, but it's a matter of style.
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 9 years ago.
As long as I don't call the function, everything is fine, but once I call the function I get an unresolved external symbol. All of my classes are in the SSE namespace (my own) and have worked fine up until now. Let me show.
#include "SDL.h"
#include "Game.h"
#include "GameObject.h"
#include <tchar.h>
SSE::Game Pong;
int _tmain(int argc, char* argv[])
{
SSE::GameObject* object;
Pong.Initialize("Pong!");
object = Pong.Objects().ObjectCreate<SSE::GameObject>();
while (!Pong.bQuit)
{
Pong.Update();
Pong.Draw();
}
return 0;
}
This is where I call the function. Game is a class that runs the behind the scenes work for me (everything's fine with that class), Game.Objects() returns the Game's ObjectManager which is in charge of creating and deleting objects as well as giving objects their components. ObjectCreate is a template function which returns a pointer to the new object created.
From the ObjectManager's .cpp file:
template <class G>G* ObjectManager::ObjectCreate()
{
ObjectList* tempObjList;
tempObjList = new tempObjList();
tempObjList->objectType = G->ClassName();
tempObjList->objectTypeNumber = 0;
for (unsigned int i = 0; i < v_objList.size(); i++;)
{
if (v_objList[i]->objectType == tempObjList->objectType)
tempObjList->objectTypeNumber++;
}
tempObjList->gameObject = new G(tempObjList->objectType + "_" + tempObjList->objectTypeNumber);
v_objList.push_back(tempObjList);
if (v_objList.back() != tempObjList)
{
delete tempObjList;
return NULL;
}
return v_objList.back();
}
This assigns a unique name for the new GameObject and creates it in memory, then stores it into a vector. One other thing to mention is I've been getting this unresolved external symbol error for many of the ObjectManager and GameObject functions similar to this one, but just the same only if I call them in code.
Just for reference, the error is:
Error 2 error LNK2019: unresolved external symbol "public: class SSE::GameObject * __thiscall SSE::ObjectManager::ObjectCreate(void)" (??$ObjectCreate#VGameObject#SSE###ObjectManager#SSE##QAEPAVGameObject#1#XZ) referenced in function _SDL_main C:\SDL\SimpleStateEngine\SSE\main.obj SSE
Let me know if you need anything else, I've been searching for hours.
You've fallen into the common trap of defining a template function in a cpp file.
You need to define the function anywhere the calling code can see it, because it's only instantiated when it's used with specific template parameters.
Your other option is to instantiate it specifically as ObjectCreate<SSE::GameObject> in your cpp file.
What you've done is define how it could be instantiated in ObjectManager.cpp and called it as if it were instantiated in another cpp file.
This question already has answers here:
Unresolved external symbol on static class members
(6 answers)
Closed 10 years ago.
It is very important that my function is static, I need to access and modify another static/non-static class member in order to print it out later. How can I do that?
Flow
Class is initiated
Constructor sets variable to something using internal function that must be static
Some time later I print that variable
Example code
#include <iostream>
class MyClass
{
public:
static int s;
static void set()
{
MyClass::s = 5;
}
int get()
{
return MyClass::s;
}
MyClass()
{
this->set();
}
};
void main()
{
auto a = new MyClass();
a->set(); // Error
std::cout << a->get() << std::endl; // Error
system("pause");
}
Error
LNK2001: unresolved external symbol "public: static int MyClass::s" (?s#MyClass##2HA)
LNK1120: 1 unresolved externals
You have declared your static variable, but you have not defined it.
Non-static member variables are created and destroyed as the containing object is created and destroyed.
Static members, however, need to be created independently of object creation.
Add this code to create the int MyClass::s:
int MyClass::s;
Addendum:
C++17 adds inline variables, allowing you code to work with a smaller change:
static inline int s; // You can also assign it an initial value here
^^^^^^