I am fairly new to cpp but have been in c# for a while. I am trying to run a simple console application but I receive this LNK2001 error message.
I have the main.cpp, and have added another class, Zeus, with files, Zeus.h and Zeus.cpp.
Here is the main.cpp:
#include "Zeus.h"
#include <iostream>
int main()
{
Zeus::tick = 25.0;
using std::cout;
cout << "nothing";
}
Here is the Zeus.h:
static class Zeus
{
public:
static void testing(void);
public:
static double tick;
};
And here is the Zeus.cpp:
void Zeus::testing(void)
{
//Doesnt get this far
//But eventually something like
// cout << "test " << Zeus::tick;
}
And here is the error message:
Error 20 error LNK2001: unresolved external symbol "public: static double Zeus::tick"
Thanks,
You need to define Zeus::tick, typically you would to that in the in the Zeus.cpp file. You have only declared it.
double Zeus::tick = 0.0;
Also, there is no static class in C++.
As an aside, free functions can be put in namespaces, as opposed to being static functions of classes. This is the preferred way in C++, unless there are strong reasons for the function to be static.
namespace Dionysus {
void testing();
}
As the error message says: there's no definition of Zeus::tick. Add this to Zeus.cpp:
double Zeus::tick;
Oh, and in Zeus.h remove the static from
static class Zeus
In the main() function you have, what do you mean by a statement Zeus::tick = 25.0;?
Zeus is a class. So to access the individual elements of it you need to create its instance. Its just like a structure where you first create its instance to access its individual elements.
Try the following:
int main() {
Zeus myobject;
myobject.tick = 25.0;
/* Rest of the definition */
}
Related
I am new to C++ but not to programming. I'm developing a plugin and learning the language at the same time. The plugin is for old software but still being used, so I'm using VS2015 and an SDK to match. I'm having a problem that I just don't know enough to solve but I know that it's the result of something that I'm doing wrong or don't understand. Please also consider that I'm using a third party SDK, with only .H/.HPP files and an occasional .CPP, but that's it. Everything else is wrapped in their libraries. Therefore, I don't have the liberty to change any behavior.
My code snippets are parts of their headers (can't change) and the .cpp is my modified sample code that comes along with their SDK and which I'm using as my base. It is also the area of code that causes the link error. Their samples all work, I can compile them and run them no problem. My code also works and is doing what I want. Things only break when I use my modified code. The reason I'm doing this is because I need access to the message passed into the plugin and can't find any other way to get it other than to try and override "PluginMain". The original sample code actually does call into PluginSetup.cpp because it runs other code within it as setup prior to continuing on. I've only posted the part of my code which is my attempt to override the function as I mentioned and I just included the variable declaration that causes the error. If I comment my variable declaration and other code related to it, program compiles and works again. If I move the variable declaration to another .cpp file in my codebase, code compiles no problem. It just don't like being in PluginSetup.cpp but part from maybe the main.cpp file (which I can't do anything with), PluginSetup.cpp is the first that gets called. So this is where I chose to put my override.
Am I using the friend function correctly? As you can see from the codebase, they've made the ctor as well as the friend function private.
This may also go hand in hand with a question I asked before on how to instantiate a class from this implementation using private friend function and ctors?
Hopefully, what I've posted is enough to give someone all that's needed to figure out what the problem might be.
ns1ns2Main.h
namespace ns1
{
namespace ns2
{
class Plugin;
...
}
}
extern "C" __declspec(dllexport) __MainError PluginMain(const char* caller_, const char* selector_, void* message_);
ns1ns2Plugin.h
#include "ns1ns2Main.h"
namespace ns1
{
namespace ns2
{
class Plugin
{
Public:
static Plugin* const instance();
private:
friend __MainError (::PluginMain) (const char*, const char*, void*);
Plugin();
Plugin(const Plugin&);
virtual ~Plugin();
};
}
}
PluginSetup.cpp
#include "ns1ns2Main.h"
#include "ns1ns2Plugin.h"
//-> My Modification Begins
__MainError (::PluginMain) (const char* caller, const char* selector, void* message)
{
ns1::ns2::Plugin plugin;
if (!plugin.instance())
{
plugin = ns1::ns2::Plugin();
}
if (strcmp(caller, kSPInterfaceCaller) == 0)
{
if (strcmp(selector, kSPInterfaceStartupSelector) == 0)
{
bool bStatus = ns1::ns2::pluginSetup(&plugin);
if (bStatus)
{
plugin_ = clpcsx::Plugin::instance();
plugin_->startup();
}
}
else if (strcmp(selector, kSPInterfaceShutdownSelector) == 0)
{
plugin_ = clpcsx::Plugin::instance();
plugin_->shutdown();
}
}
return error;
}
//<- My Modification Ends
namespace ns1
{
namespace ns2
{
void pluginLoaded()
{
// no-op
}
bool pluginSetup(Plugin* const plugin)
{
clpcsx::Plugin::create(plugin);
plugin->setStartupCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, startup));
plugin->setPostStartupCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, postStartup));
plugin->setPreShutdownCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, preShutdown));
plugin->setShutdownCallback(NS1_NS2_CALLBACK(clpcsx::Plugin, CLPCSX_PLUG_INST, shutdown));
return true;
}
void pluginDestroy(Plugin* const plugin)
{
clpcsx::Plugin::destroy();
}
}
}
Link Error
1>PluginSetup.obj : error LNK2019: unresolved external symbol "private: __cdecl ns1::ns2::Plugin::Plugin(void)" (??0Plugin#ns2#ns1##AEAA#XZ) referenced in function PluginMain
You have to tell the linker to include the libraries. Since this is VS you can add to the main .cpp file
#pragma comment(lib, "xxxx.lib")
where 'xxxx.lib' is the name of the library that has those ns functions. You need to make sure they are in the VS linker path too
I have been trying for hours to get rid of my errors but it won't go away, i have looked up other posts but nothing seems to work.
I got my .H file with something like this:
using namespace std;
class common
{
public:
common();
static double common::s_a;
static double common::s_b;
Then i got a .CPP file where i've defined those variables like this:
#include "common.h"
common::common()
{
common::s_a = 100;
common::s_b = 100;
}
Then i got this error message(actual variable name instead of a)
common.obj : error LNK2001: unresolved external symbol "public: static
double common::s_playerMaxHealth" (?s_playerMaxHealth#common##2NA)
EDIT : The problem is static, if i remove static i don't have the error anymore. However i need to use static for it to work as intented.
You must define these variables like so (in your .cpp file, outside of any function):
double common::s_a;
double common::s_b;
This is a declaration (not a definition):
class common
{
static double common::s_a;
static double common::s_b;
This is a use (not a definition either):
common::common()
{
common::s_a = 100;
common::s_b = 100;
}
I'm currently struggeling with a compilerproblem. The problem is, that i use one of the MoSync example apps called "European Countries" (written in c++) to write my own. But when i compile the modified code, it gives me following error in response:
Controller.cpp:24: Error: Unresolved symbol '__ZTVN13Flightmanager6FlightE',
I already had a look at the example several times and i already copied the code from the example to mine, but it doesn't solve any problems.
In paticutlar i might understand what the error means (i do have c experience), but i've never seen such structured error. I also looked at namespacing conventions but there shouldn't be any problems.
//Flight.h
namespace Flightmanager
{
class Flight
{
public:
static int flightCounter;
/**
* The constructor creates the user interface.
*/
Flight(char *flightnumber, char *gate, char *departure, char *additionalinfo, char *destinationairport, char *destinationairportshort) {
this->_id = flightCounter;
flightCounter ++;
this->_flightnumber = flightnumber;
this->_gate = gate;
this->_departure = departure;
this->_additionalinfo = additionalinfo;
this->_destinationairport = destinationairport;
this->_destinationairportshort = destinationairportshort;
}
virtual ~Flight();
}
//Controller.h
#include [all other includes]
#include "../Model/Flight.h"
namespace Flightmanager
{
Controller::Controller():
mFlightArray(NULL),
mCurrentlyShownScreen(NULL)
{
initScreenSizeConstants();
initPlatformType();
//error: Unresolved symbol '__TZVN13Flightmanager6FlightE'.
initData();
//error: Unresoled symbol '__TZVN13Flightmanager6Flight13flightCounterE'.
mFlightTableView = new TableViewController(*this);//error: Unresoled symbol '__TZVN13Flightmanager6Flight13flightCounterE'.
mFlightDetailView = new DetailViewController();
}
}
I use MoSync Version 3.2
Build date: 121219-1556
Thx
You need to link in something that has definitions for:
Flight::flightCounter
Flight::~Flight()
whether that's a .o object file for Flight.cpp (or some source file) or a library depends on your project.
I got a MFC app that is writing a huge hierarichy of objects to disk.
To make sense of what is being written I thought of logging all the calls to archive << via stream insertion and .write method by replacing those with macros
#pragma once
#ifndef LOGMAGIC
#define LOGMAGIC
class LogTab
{
public:
static int LogIndentCount;
LogTab()
{
LogIndentCount++;
}
~LogTab()
{
LogIndentCount--;
}
};
#define ARINSERT(AR,OBJ) TRACE( "%*s %s\n", LogTab::LogIndentCount, #OBJ); AR << OBJ;
#define ARWRITE(AR,OBJ,SIZE) TRACE("%*s %s\n", LogTab::LogIndentCount, #OBJ); AR.write(OBJ, SIZE);
#endif
So I created above snippet of code and put it in stdafx.h but I'm getting the following error:
Error 1 error LNK2001: unresolved external symbol "public: static int
LogTab::LogIndentCount" (?LogIndentCount#LogTab##2HA)
What am I doing wrong?
Is there a better way to achieve what I am doing?
You have to define LogTab::LogIndentCount in any one of the .cpp files as,
#include"LogTab.h"
//...
int LogTab::LogIndentCount = 0;
[As a side note, if it's a multi threaded system which is using this class then you may think of making LogIndentCount synchronized (thread safe)]
A static variable must be explicitly initialized.
Very simply put:
I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.
Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.
class test
{
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
test::test()
{
X = 1;
Y = 2;
}
I'm new to C++ so go easy on me. Why can't I do this?
If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
unsigned char test::X;
unsigned char test::Y;
somewhere. You might want to also initialize a static member
unsigned char test::X = 4;
and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)
Static data members declarations in the class declaration are not definition of them.
To define them you should do this in the .CPP file to avoid duplicated symbols.
The only data you can declare and define is integral static constants.
(Values of enums can be used as constant values as well)
You might want to rewrite your code as:
class test {
public:
const static unsigned char X = 1;
const static unsigned char Y = 2;
...
test();
};
test::test() {
}
If you want to have ability to modify you static variables (in other words when it is inappropriate to declare them as const), you can separate you code between .H and .CPP in the following way:
.H :
class test {
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
.CPP :
unsigned char test::X = 1;
unsigned char test::Y = 2;
test::test()
{
// constructor is empty.
// We don't initialize static data member here,
// because static data initialization will happen on every constructor call.
}
in my case, I declared one static variable in .h file, like
//myClass.h
class myClass
{
static int m_nMyVar;
static void myFunc();
}
and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:
error LNK2001: unresolved external symbol "public: static class...
The link error related cpp file looks like:
//myClass.cpp
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}
So I add below code on the top of myClass.cpp
//myClass.cpp
int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
void myClass::myFunc()
{
myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
}
then LNK2001 is gone.
Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:
For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.
When we declare a static variable in a class, it is shared by all the objects of that class. As static variables are initialized only once they are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).
In the below example, static variable counter is a member of the class Demo. Note how it is initialized explicitly outside the class with the initial value = 0.
#include <iostream>
#include <string>
using namespace std;
class Demo{
int var;
static int counter;
public:
Demo(int var):var(var){
cout<<"Counter = "<<counter<<endl;
counter++;
}
};
int Demo::counter = 0; //static variable initialisation
int main()
{
Demo d(2), d1(10),d3(1);
}
Output:
Count = 0
Count = 1
Count = 2
In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]