C++ Static Variable Declaration Weird Linker Error [duplicate] - c++

This question already has answers here:
Unresolved external symbol on static class members
(6 answers)
Closed 5 years ago.
I want to count the ammount of objects which have been created by using a certain constructor. I have done this in languages like C# before so I created a static int variable which I'm incrementing in the constructor.
Before I show you the code - here is the compilement error:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "private: static int Bill::count_of_created_bills" (?count_of_created_bills#Bill##0HA) Ausgabenverwaltung c:\Users\xy\documents\visual studio 2017\Projects\Ausgabenverwaltung\Ausgabenverwaltung\Ausgabenverwaltung.obj 1
Here is the code:
#pragma once
class Bill
{
private:
static int count_of_created_bills;
int id; // Unique Identification
double ammount; // Ammount of bill
int month; // Month of bill (January = 0, February = 1 ...)
int type_of_spending; // Type of spending (Food = 0 ...)
public:
Bill(int a, int m, int t):ammount(a), month(m), type_of_spending(t)
{
count_of_created_bills++;
id = count_of_created_bills;
}
};
The compilement error occurrs if I'm including this line:
Bill b(1, 2, 3);

you forgot to add the initialization:
Bill::Bill(int a, int m, int t):ammount(a), month(m), type_of_spending(t)
{
std::cout << "::Ros-App!" << Foo::count_of_created_bills << std::endl;
Foo::count_of_created_bills++;
id = count_of_created_bills;
}
int Bill::count_of_created_bills = 0;

Related

Link time error happened on C++ class codes [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Undefined reference to WinMain (C++ MinGW)
(5 answers)
Closed last month.
In date.h, I wrote:
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <ctime>
class Date
{
int year,month,day;
public:
Date();
Date(int y, int m, int d)
: year(y), month(m), day(d) {}
~Date() = default;
int getYear() { return year; }
int getMonth() { return month; }
int getDay() { return day; }
bool isLeapyear() { return (year % 400 == 0) || (year % 4 == 0 & year % 100 != 0); }
void print() { std::cout << year << "." << month << "." << day << std::endl; }
};
#endif // DATE_H
and in date.cpp, I wrote:
#include "date.h"
Date::Date()
{
time_t ltime = time(NULL);
tm *today = localtime(&ltime);
year = today->tm_year + 1900;
month = today->tm_mon + 1;
day = today->tm_mday;
}
There are no compiling error with this code, but I got a link time error when I tried to run this code:
undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status
What has caused the error and how can I fix it?
As other commented the problem is that you created a class which is not executable by itself. You created a library that you can use in other C++ programs, so it compiles fine but it cannot run by itself, that's why you get the error while trying to run the compiled binary. In C++ you have to execute the code of the classes from a main function.
The simplest way to fix it would be to add main.cpp:
#include "date.h"
int main(void){
Date d = Date(2023, 1, 23);
d.print();
}

'unresolved external symbol' then trying to access 'static set<int>' [duplicate]

This question already has answers here:
How to initialize private static members in C++?
(18 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I know that unresolved external symbol means that compiler can't find definition.
I got this error
Severity Code Description Project File Line
Error LNK2001 unresolved external symbol "private: static class std::set,class std::allocator > VirtualWorld::vWords" (?vWords#VirtualWorld##0V?$set#HU?$less#H#std##V?$allocator#H#2##std##A) ConsoleApplication11 c:\Users\Laptop\documents\visual studio 2015\Projects\ConsoleApplication11\ConsoleApplication11\Source.obj 1
with this code below (this code is fragments, but it's still generates this error)
#include <set>
#ifndef _TYPE_ID
#define _TYPE_ID
typedef unsigned int Id;
#endif
#ifndef _CLASS_VIRTUALWORLD
#define _CLASS_VIRTUALWORLD
class VirtualWorld
{
private:
static Id freeCounter;
static std::set<Id> vWorlds;
bool holding;
Id virtualWorldId;
static Id hold();
static void release(const Id & i);
public:
VirtualWorld();
~VirtualWorld();
Id getInstance();
void forceRelease();
};
#endif
int main() {
VirtualWorld virWorld;
return 0;
}
Id VirtualWorld::freeCounter = 1;
Id VirtualWorld::hold() {
std::set<Id>::iterator iter = vWorlds.lower_bound(freeCounter);
while (iter != vWorlds.end() && *iter == freeCounter)
{
++iter;
++freeCounter;
}
return freeCounter++;
}
void VirtualWorld::release(const Id & i) {
vWorlds.erase(i);
freeCounter = 1;
}
VirtualWorld::VirtualWorld() : holding(false) { }
VirtualWorld::~VirtualWorld()
{
if (holding) {
release(virtualWorldId);
}
}
Id VirtualWorld::getInstance() {
if (!holding) {
virtualWorldId = hold();
holding = true;
}
return virtualWorldId;
}
void VirtualWorld::forceRelease() {
if (holding) {
release(virtualWorldId);
holding = false;
}
}
I researched that I'm getting this error then trying to access vWorlds in hold() and release(int) functions. Why I'm getting this error and what should I change ?

error LNK2019: unresolved external symbol, cannot not link with the cpp file i coded [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 7 years ago.
I start learning C++ in school and this error appear.
1>Bettle_Dice.obj : error LNK2019: unresolved external symbol "public: int __thiscall Beetle::checkcom(void)" (?checkcom#Beetle##QAEHXZ) referenced in function _main
I have include other header files and cpp files, I don understand why only this file have problem please help
Below is my code
main.cpp
#include "stdafx.h"
#include "beetle.h"
#include "dice.h"
#include "player.h"
#include <iostream>
using namespace std;
int main()
{
Player p; //declare Class to a variable
Dice d;
Beetle btle;
int temp;
cout << "Number of players?" << endl;
cin >> temp;
p.Num(temp); //store the number of player into class
//cout << p.getNumPlayers() <<endl;
cout << "Start game!!" <<endl;
temp = btle.checkcom();
while(temp != 1)
{
for(int i=0;i<p.getNumPlayers();i++)
{
temp = d.roll();
cout <<"Your roll number:"<< temp;
}
}
return 0;
}
beetle.h
class Beetle
{
private:
int body,head,ante,leg,eye,tail;
public:
int completion();
int checkcom();
int getBody() { return body;};
int getHead() { return head;};
int getAnte() { return ante;};
int getLeg() { return leg;};
int getEye() { return eye;};
int getTail() { return tail;};
};
Beetle.cpp
#include "stdafx.h"
#include "beetle.h"
int completion()
{
return 0;
}
int checkcom()
{
Beetle btle;
int flag = 0;
if(btle.getBody() == 1 && btle.getHead() == 1 && btle.getAnte() == 2 && btle.getEye() == 2 && btle.getLeg() ==6 && btle.getTail() == 1)
flag = 1;
return flag;
}
I checked some solution on the internet, some are saying is the library problem, but this file is not a built-in function. I guess it is not the problem of the library. I tried to include the beetle.obj file to it and the debugger said it is included already and duplicate definition.
In the other file, i do not have "bettle" this word. It should not be the problem of double declaration or duplicate class.
I have no idea what the problem is. Please help.
You need to prefix the signature of your class functions with the class name Beetle::
Otherwise the compiler just thinks those functions are global functions, not member functions.

Error Code LNK2019 & LNK1120 [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 7 years ago.
I create this file over and over and cant seem to see why I'm getting this error. I tried going to the line where the code is but the format seem correct I may just need another set of eyes .
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void readString(char*, int);
void changeToUppercase(char*, int);
void displayStringInUppercase(char*, int);
int main()
{
int arraySize;
char* characterArray;
cout << "Enter the size of dynamic array: ";
cin >> arraySize;
characterArray = new char[arraySize];
readString(characterArray, arraySize);
changeToUppercase(characterArray, arraySize);
displayStringInUppercase(characterArray, arraySize);
delete [] characterArray;
system ("pause");
return 0;
}
void changeToUppercase(char* characterArray, int arraySize)
{
for(int i = 0; i < arraySize; i++)
characterArray[i] = toupper(characterArray[i]);
}
void displayStringInUppercase(char* characterArray, int arraySize)
{
cout << "\nThestring inupper case letters: ";
for(int i = 0; i < arraySize; i++)
characterArray[i] = toupper(characterArray[i]);
}
This is the error codes that keep popping up:
error LNK2019: unresolved external symbol "void __cdecl readString(char *,int)" (?readString##YAXPADH#Z) referenced in function _main
fatal error LNK1120: 1 unresolved externals
You use a forward declaration: void readString(char*, int); but then never actually define this function.
Define your readString function later in your code like...
void readString(char* str, int a)
{
// do stuff
}
You are missing the readString function. You have a forward declaration that satisfies the compiler here
void readString(char*, int);
But no actual implementation of the function to satisfy the linker when it tries to put your program together. You need something along the lines of
void readString(char* characterArray, int arraySize)
{
// do stuff here
}

Link error 2019, prototypes are in header file though

I'm new to c++ and was just trying to do a question that involves 3 files.
I got a header file with a namespace that declares a structure and some prototypes. In definitions.cpp file, I have all the function definitions. Then the main.cpp file, just creates a few structures, calls some functions to fill the structures, then calls another function to display the structures.
The problem I have is it gives me an unresolved external error. From what I can gather I think the compiler is complaining that it cant find the prototypes for the functions being called in main.cpp - the overloaded setStruct() and the showStruct().
But I thought when I included the header.h file and declared the functions with the using declaration, in main.cpp, it gave the compiler access to the prototypes stored in the header file?
Header.h
#ifndef header_h
#define header_h
namespace SALES
{
const int QUARTERS = 4;
struct Sales
{
double sales[QUARTERS];
double average;
double max;
double min;
};
void setSales(Sales & s, const double ar[], int n);
void setSales(Sales & s);
void showSales(const Sales & s);
}
#endif
Definitions.cpp
#include<iostream>
#include"header.h"
using SALES::Sales;
using SALES::QUARTERS;
double max(Sales & s) //find max sale value in sales array
{
double maxVal = s.sales[0];
for(int i = 1; i<4;i++)
{
if(s.sales[i]>maxVal)
{
maxVal = s.sales[i];
}
}
return maxVal;
}
double min(Sales & s) //find min sale value in sales array
{
double minVal = s.sales[0];
for(int i = 1; i<4;i++)
{
if(s.sales[i]<minVal)
{
minVal = s.sales[i];
}
}
return minVal;
}
void setSales(Sales & s) // fill sales structure interactivly
{
std::cout<< "Please enter the sales for the yearly quarters.\n";
for(int i = 0;i<QUARTERS;i++)
{
std::cout<< "Quater "<<i+1<<": ";
while(!(std::cin>>s.sales[i]))
{
std::cout<<"Please enter valid input\n";
std::cout<< "Quater "<<i+1<<": ";
std::cin.clear();
std::cin.ignore();
}
}
s.average = ((s.sales[0]+s.sales[1]+s.sales[2]+s.sales[3])/4);
s.max = max(s);
s.min = min(s);
}
void setSales(Sales & s, const double ar[], int n) // fill sales structure non interactivly
{
for(int i = 0;i<n;i++)
{
s.sales[i] = ar[i];
}
for(int i = n;i<QUARTERS;i++)
{
s.sales[i] = 0;
}
s.average = ((s.sales[0]+s.sales[1]+s.sales[2]+s.sales[3])/4);
s.max = max(s);
s.min = min(s);
}
void showSales(const Sales & s) // display structure
{
std::cout<< "\nSales for the year\n";
for(int i = 0;i<QUARTERS;i++)
{
std::cout<<"Quarter "<<i+1<<": $"<<s.sales[i];
}
std::cout<<"Max Sale: "<<s.max<<std::endl;
std::cout<<"Min Sale: "<<s.min<<std::endl;
std::cout<<"Average of sales: "<<s.average<<std::endl;
}
Main.cpp
#include<iostream>
#include"header.h"
using SALES::Sales;
using SALES::setSales;
using SALES::showSales;
int main()
{
double Sales1[4] = {453.50, 654.60, 340.20, 500.30};
Sales Year1;
Sales Year2;
setSales(Year1, Sales1, 3);
setSales(Year2);
showSales(Year1);
showSales(Year2);
return 0;
}
Error
1>------ Build started: Project: Myfirst, Configuration: Debug Win32 ------
1> Main.cpp
1>Main.obj : error LNK2019: unresolved external symbol "void __cdecl SALES::setSales(struct SALES::Sales &,double const * const,int)" (?setSales#SALES##YAXAAUSales#1#QBNH#Z) referenced in function _main
1>Main.obj : error LNK2019: unresolved external symbol "void __cdecl SALES::setSales(struct SALES::Sales &)" (?setSales#SALES##YAXAAUSales#1##Z) referenced in function _main
1>Main.obj : error LNK2019: unresolved external symbol "void __cdecl SALES::showSales(struct SALES::Sales const &)" (?showSales#SALES##YAXABUSales#1##Z) referenced in function _main
1>E:\Documents\Uni\Programming\C++ starter projects\Myfirst\Debug\Myfirst.exe : fatal error LNK1120: 3 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Any help would be great, thanks.
When you define the setSales etc functions, you need to tell the compiler that they are in the SALES namespace. Putting
namespace SALES
{
// functions here
}
will do it.
You are currently defining your functions outside of any namespace, and that is the reason for the linker not finding the definitions within the namespace where those functions are declared and recognized.
The fix would be to wrap the functions in your implementation file - Definitions.cpp -, with the namespace similarly how you are doing it in the header file.
This is what I would write if I were you:
namespace SALES
{
...
void setSales(Sales & s) // fill sales structure interactivly
...
std::cout<<"Average of sales: "<<s.average<<std::endl;
}
}
If you do not put the rest (your min and max) into the namespace, use the :: scope specifier just in case, although I would suggest to put everything into your own namespace.