linker error with classes in c++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I have created this code
class Game{
static SDL_Surface* screen;
public:
//Initiate Game(SDL_Graphics, folder for output.....)
static void initialize();
static void initializeScreen();
};
void Game::initializeScreen()
{
Game::screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_DOUBLEBUF |SDL_HWSURFACE |SDL_SWSURFACE);
SDL_Init(SDL_INIT_VIDEO);
Game::screen == NULL ? printf("SDL_Init failed: %s\n", SDL_GetError()):printf("SDL_Init initialized\n");
SDL_WM_SetCaption("SDL Animation", "SDL Animation");
}
It compiles but I get e linker error, how can I fix this?
1>game.obj : error LNK2001: unresolved external symbol "private: static struct SDL_Surface * Game::screen" (?screen#Game##0PAUSDL_Surface##A)
Edit: This is how I fixed it, in game.cpp
added this
SDL_Surface* Game::screen;
outside of any function*

You have to define static (variable) members (not functions) in seperate source files(*.cpp) and link against them.
for example:
//MyClass.h
class MyClass {
static int x;
};
//MyClass.cpp
#include "MyClass.h"
int MyClass::x;

You need to add the following definition in your cpp file SDL_Surface* Game::screen = NULL.
Here is an example code where you can have a static variable without defining it in the cpp file using a function.
#include <iostream>
struct Lazy {
static int& GetValue() {
static int a = 0;
return a;
}
};
int main() {
std::cout << Lazy::GetValue() << std::endl;
int& a = Lazy::GetValue();
a = 1;
std::cout << Lazy::GetValue() << std::endl;
}

Related

error using static variable unresolved external symbol / undefined reference [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
I am using static variable. After referring to Unresolved external symbol on static class members, I modified the program with Abc::ct
#include <iostream>
class Abc
{
private:
static unsigned int ct;
public:
void f1()
{
for (int i = 0; i < 5; ++i)
f2();
}
void f2() {
Abc::ct = 0;
if (Abc::ct == 0)
std::cout << "Zero iteration\n";
std::cout << Abc::ct << "\t";
++Abc::ct;
}
};
int main()
{
Abc obj;
obj.f1();
}
but getting error as error LNK2001: unresolved external symbol "private: static unsigned int Abc::ct" in MSVC or undefined reference to Abc::ct in g++. How can I define static variable in class Abc?
You declared your static variable, but you did not define and initialize it. Above main(), but outside of your class, add the following line:
unsigned int Abc::ct = 0;
or, if you are using C++17, you can change your:
static unsigned int ct;
to:
static inline unsigned int ct = 0;
You have to define it:
unsigned int Abc::ct = 0;
Demo

How to call static library function in a C++ class? [duplicate]

This question already has answers here:
How to implement static class member functions in *.cpp file?
(7 answers)
What does "static" mean in C?
(20 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
I have class whose header file is defined as:
namespace mip {
class CustomStatic {
public:
static const char* GetVersion();
};
}
And class file is defined as:
#include "CustomStatic.h"
namespace mip {
static const char* GetVersion() {
return "hello";
}
}
I am accessing this static function from my main class
#include "CustomStatic.h"
#include <iostream>
using std::cout;
using mip::CustomStatic;
int main() {
const char *msg = mip::CustomStatic::GetVersion();
cout << "Version " << msg << "\n";
}
When I try to compile it using-
g++ -std=c++11 -I CustomStatic.h MainApp.cpp CustomStatic.cpp
I am getting error as:
Undefined symbols for architecture x86_64:
"mip::CustomStatic::GetVersion()", referenced from:
_main in MainApp-feb286.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code
1 (use -v to see invocation)
your static function is not properly implemented in the cpp file...
you need to do something like
//.h
namespace mip
{
class CustomStatic
{
public:
static const char* GetVersion();
};
}
//.cpp -> note that no static keyword is required...
namespace mip
{
const char* CustomStatic::GetVersion()
{
return "hello";
}
}
//use
int main(int argc, char *argv[])
{
const char* msg{mip::CustomStatic::GetVersion()};
cout << "Version " << msg << "\n";
}

Unresolved external symbol "public: int myclass::get_a (void)" How do I resolve this code? Noobie Q

Noobie programmer here learning C++ for the first time. The following is excerpted code from Teach Yourself C++ 3rd Edition.
I'm dying help me, I'm learning about classes, but I can't get this code to compile on visual studio or on Code::Blocks. :(
//#include "stdafx.h"
#include <iostream>
//I understand this. Headers, etc.
using namespace std;
//and this, name traffic management system
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a();
};
/*I understand int a is private/inaccessible from the rest of the code
and void set_a(int num) is the dummy function.*/
void myclass::set_a(int num)
//not sure what this is
{
a = num;
}
/*self explanatory*/
int _tmain(int argc, _TCHAR* argv[])
{
myclass ob1, ob2;
ob1.set_a(10);
ob2.set_a(99);
cout << ob1.get_a() << "\n";
cout << ob2.get_a() << "\n";
return -5;
}
/*This is just supposed to output the number 10 and 99 right?? So why isn't it?*/
On Visual Studio the full error description is:
Error 1 error LNK2019: unresolved external symbol "public: int __thiscall myclass::get_a(void)" (?get_a#myclass##QAEHXZ) referenced in function _wmain c:\Users\bernardo pliego\documents\visual studio 2013\Projects\Chapter 1.5\Chapter 1.5\Chapter 1.5.obj Chapter 1.5
On Code::Blocks I receive the following error:
In function 'main':
undefined reference to 'my_class::get_a()'
I am in dire need of help, can someone explain this to me?
Because you don't define get_a, you only declare it. Add a definition like this:
int myclass::get_a() { return a; }
Or just define it inline:
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a() { return a };
};
You don't ever define int get_a(); so you get an error at link-time.
Include this just above your (rather hubristic) /*self explanatory*/ comment
int myclass::get_a()
{
return a;
}

C++ How to set a private class member in a namespace within a static library?

Hi there fellow nerds,
i got a problem while tryin to code a static library. Im trying to set a private class member with a public class function. The class is located in a namespace. When i try to compile the example program (namespace_test) i get a LNK2001 Error stating a not resolved external symbol.
(Fehler 1 error LNK2001: Nicht aufgelöstes externes Symbol ""private: static bool ns_test::CTest::m_bPrivateMember" (?m_bPrivateMember#CTest#ns_test##0_NA)". ...\ns_test\namespace_test\namespace_test_api.lib(CTest.obj) namespace_test
)
How can i correctly implement that function?
Here is my code:
namespace_test_api.proj
namespace.h
namespace ns_test
{
class CTest
{
public:
CTest();
~CTest();
static void SetPrivateMember(bool i_bPrivateMember);
static bool bGetPrivateMember();
private:
static bool m_bPrivateMember;
};
}
CTest.cpp
#include "namespace.h"
namespace ns_test
{
CTest::CTest()
{
}
CTest::~CTest()
{
}
void CTest::SetPrivateMember(bool i_bPrivateMember)
{
CTest::m_bPrivateMember = i_bPrivateMember;
}
bool CTest::bGetPrivateMember()
{
return CTest::m_bPrivateMember;
}
}
namepsace_test.proj
namspace.h
namespace ns_test
{
class CTest
{
public:
CTest();
~CTest();
static void SetPrivateMember(bool i_bPrivateMember);
static bool bGetPrivateMember();
private:
static bool m_bPrivateMember;
};
}
main.cpp
#include <Windows.h>
#include <iostream>
#include "namespace.h"
#pragma comment (lib, "namespace_test_api.lib")
int main()
{
ns_test::CTest::SetPrivateMember(true);
std::cout << "PrivateMember: " << ns_test::CTest::bGetPrivateMember() << std::endl;
system("pause");
}
In CTest.cpp, you need to add the line:
bool ns_test::CTest::m_bPrivateMember;
This defines the static member, the entry in the class only declares it.
Note that the above will initialise it with false. You may want to make that explicit, or true:
bool ns_test::CTest::m_bPrivateMember = true;
Note this is an example of the One Definition Rule: you need to define each global exactly once.

C++ classes getting error (SDL) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
Hi I am noob with classes and I just started learning them. I need help with this code as I have no idea why I get this error.
Here is my Code
main.cpp
#include "stdafx.h"
#include "player.h"
SDL_Surface* screen = NULL;
void init()
{
SDL_Init( SDL_INIT_VIDEO );
//Set up screen
screen = SDL_SetVideoMode( 640, 480, 32, SDL_DOUBLEBUF |SDL_HWSURFACE |SDL_SWSURFACE);
//SDL_BlitSurface( hello, NULL, screen, NULL );
_putenv("SDL_VIDEO_CENTERED=1"); // Center the window
SDL_Init(SDL_INIT_VIDEO);
SDL_WM_SetCaption("SDL Animation", "SDL Animation");
//screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_DOUBLEBUF |SDL_HWSURFACE |SDL_SWSURFACE);
SDL_EnableKeyRepeat(0, 1600000);
if(screen == NULL){
printf("SDL_Init failed: %s\n", SDL_GetError());
}
}
int _tmain(int argc, _TCHAR* argv[])
{
init();
//SDL_Surface* sprite = SDL_BlitSurface(sprite,rcSprite, screen, &rcSprite);
Player player;
//Update Screen
SDL_Flip( screen );
SDL_FreeSurface(screen);
return 0;
}
player.h
#ifndef PLAYER_H
#define PLAYER_H
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_TTF.h"
class Player
{
public:
Player (){
HP = 20;
playerScore = 0;
playerSpeed = 10;
playerJump = 20;
}
~Player();
int getScore() { return playerScore;}
void setSpeed(int speed) { int playerSpeed = speed;}
void setJump (int jump) {playerJump = jump;}
void movePlayer(int x ,int y);
void runRightAnim (SDL_Rect* clip);
void runLeftAnim (SDL_Rect* clip);
void drawPlayer(int x, int y, SDL_Surface* source, SDL_Surface* destination);
static SDL_Rect sprite;
private:
static int HP;
static int playerScore;
static int playerSpeed;
static int playerJump;
static int animRate;
};
#endif
and the last one player.cpp
#include "stdafx.h"
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_TTF.h"
#include "player.h"
void Player::runRightAnim(SDL_Rect* clip)
{
}
void Player::runLeftAnim(SDL_Rect* clip)
{
}
void Player::drawPlayer(int x, int y, SDL_Surface* source, SDL_Surface* destination)
{
SDL_Rect dst;
dst.x = x;
dst.y = y;
SDL_BlitSurface(source,NULL,destination,&dst);
//SDL_BlitSurface(selectionCanvas, NULL, canvas, selectionRect);
}
and the error is
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Player::~Player(void)" (??1Player##QAE#XZ) referenced in function _wmain
1>main.obj : error LNK2001: unresolved external symbol "private: static int Player::playerJump" (?playerJump#Player##0HA)
1>main.obj : error LNK2001: unresolved external symbol "private: static int Player::playerSpeed" (?playerSpeed#Player##0HA)
1>main.obj : error LNK2001: unresolved external symbol "private: static int Player::playerScore" (?playerScore#Player##0HA)
1>main.obj : error LNK2001: unresolved external symbol "private: static int Player::HP" (?HP#Player##0HA)
The code is obviously not finished but I just want to get rid of this error
"unresolved external" errors occur when you declare and attempt to use a function, but you don't implement it. In particular:
1>main.obj : error LNK2019: unresolved external symbol "public:
__thiscall Player::~Player(void)" (??1Player##QAE#XZ) referenced in function _wmain
Is because though you have a declaration for Player::~Player():
class Player
{
public:
/* ... */
~Player();
This method is never implemented.
Fix this error by implementing the methods in question.
Edit: Additionally, your class has static member variables which are declared but never defined. Your declaration is here:
class Player
{
/* ... */
private:
static int HP;
static int playerScore;
static int playerSpeed;
static int playerJump;
static int animRate;
};
But this declaration does not define the variables. You must define and initialize these statics, else you will get (are getting) unresolved externals here as well.
Generally somewhere in the cpp file:
int Player::playerScore = 0;
As an aside, you are using static member variables for a class which appears to be instantiatable multiple times. If you do this:
Player a;
Player b;
to instantiate multiple Player objects, because the member variables are declared static they will each "share" the same playerScore etc. This doesn't make a lot of sense when looking at your code. You probably won't want these to be statics.