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(<ime);
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();
}
Related
This question already has answers here:
Undefined reference to static class member
(9 answers)
Undefined reference to a static member
(5 answers)
Closed last year.
Because I want my unique_ptr to be the same in all my objects, I decided to make it a static field.
After that an error has appeared:
https://pastebin.com/PPe6z0Ub
I don't really know how to fix it, I've tried searching for it online but I couldn't find anything really useful.
Code:
DBFeed.h
#pragma once
#include <vector>
#include <string>
#include <memory>
class DBFeed
{
public:
void CalculatePosts();
std::vector<std::string> GetPost();
void ClearFeed();
private:
static std::unique_ptr<std::vector<std::vector<std::string>>> m_postari;
static int m_index;
};
DBFeed.cpp
#include "DBFeed.h"
#include "DBLink.h"
int DBFeed::m_index = 0;
void DBFeed::CalculatePosts()
{
DBFeed::m_postari = std::make_unique<std::vector<std::vector<std::string>>>();
pqxx::work worker(*DBLink::GetInstance());
try
{
worker.conn().prepare("CountPostsFeed", "SELECT COUNT(id) FROM posts");
worker.conn().prepare("ReadAllPostsFeed",
"SELECT message FROM followers RIGHT JOIN posts ON followers.followed = posts.user_id WHERE followers.follower = 51 LIMIT 5 OFFSET" + std::to_string(m_index+=5)
);
pqxx::row countPostsResult = worker.exec_prepared1("CountPostsFeed");
std::string number = countPostsResult.at("count").c_str();
pqxx::result readAllPostsResult = worker.exec_prepared_n(std::stoi(number), "ReadAllPostsFeed");
for (const auto& currentPost : readAllPostsResult)
{
std::string postID = currentPost.at("id").c_str();
std::string message = currentPost.at("message").c_str();
std::string dateCreated = currentPost.at("date_created").c_str();
DBFeed::m_postari->push_back(std::vector<std::string>{postID, message, dateCreated});
}
worker.commit();
}
catch (const pqxx::unexpected_rows&)
{
throw std::runtime_error("Reading all of an users posts for feed failed");
}
}
std::vector<std::string> DBFeed::GetPost()
{
if (m_postari->empty())
{
CalculatePosts();
}
std::vector<std::string> deReturnat = m_postari->at(0);
m_postari->erase(m_postari->begin());
return deReturnat;
}
void DBFeed::ClearFeed()
{
m_index = 0;
m_postari.reset();
}
Why is this error happening and how can I fix it?
//Edit:
Fixed it by adding this by changing DBFeed.cpp's first lines as follows:
#include "DBFeed.h"
#include "DBLink.h"
int DBFeed::m_index = 0;
std::unique_ptr<std::vector<std::vector<std::string>>>
DBFeed::m_postari = std::make_unique<std::vector<std::vector<std::string>>>();
void DBFeed::CalculatePosts()
{
pqxx::work worker(*DBLink::GetInstance());
....
But I'd still like to get an explanation on why it was happening and why is it fixed now.
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 2 years ago.
I am working with my own custom header file for the first time in C++. The goal of this program is to create a dice class that can be used to create an object oriented dice game.
When I go to run my program (made of three files (header/class specification file, class implementation file, and finally the application file), I am getting an error:
undefined reference to `Die::Die(int)'
I have about six of these errors when running app.cpp, one for every time I try to access information from my Die class.
Full Error Message
My Three Files
Die.h
#ifndef DIE_H
#define DIE_H
#include <ctime>
//#include
class Die
{
private:
int numberOfSides=0;
int value=0;
public:
Die(int=6);
void setSide(int);
void roll();
int getSides();
int getValue();
};
#endif
Die.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Die.h"
using namespace std;
Die::Die(int numSides)
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Set the number of sides.
numberOfSides = numSides;
// Perform an initial roll.
roll();
}
void Die::setSide(int side=6){
if (side > 0){
numberOfSides = side;
}
else{
cout << "Invalid amount of sides\n";
exit(EXIT_FAILURE);
}
}
void Die::roll(){
const int MIN_VALUE = 1; // Minimum die value
value = (rand() % (numberOfSides - MIN_VALUE + 1)) + MIN_VALUE;
}
int Die::getSides()
{
return numberOfSides;
}
int Die::getValue()
{
return value;
}
app.cpp
#include <iostream>
#include "Die.h"
using namespace std;
bool getChoice();
void playGame(Die,Die,int &, int &);
int main()
{
int playerTotal=0;
int compTotal=0;
Die player(6);
Die computer(6);
while(getChoice()){
playGame(player, computer, playerTotal, compTotal);
getChoice();
}
}
void playGame(Die play, Die comp, int &pTotal, int &cTotal){
//add points
play.roll();
pTotal += play.getValue();
comp.roll();
cTotal += comp.getValue();
//show points each round
cout << "You have " << pTotal << " points;\n";
}
bool getChoice(){
bool choice;
cout << "Would you like to roll the dice? (Y/N): ";
cin>> choice;
return choice;
}
You should compile both app.cpp and Die.cpp at the same time:
g++ app.cpp Die.cpp
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Firstly, I am very new to C++ and have had only minimal teaching/practice, so please bear this in mind. I have created a Date class for a project I am working on. I had previously organised my code in a sloppy way, but it had functioned enough for me to write the syntax of my code effectively. After someone looked at my code I realised I needed to structure my classes better, so tried to organise my Date class into a header and cpp file. Having done so, I get a number of errors along the lines of:
'day': undeclared identifier
missing type specifier - int is assumed
Also, the Date is recognised as a type in the cpp file as it changes colour in Visual Studio, but in the header file the class is not coloured as a type.
A tutor looked through and couldn't help as to where my error was coming from, but if I remove these two files my code functions without errors so it's definitely somewhere in the scripts below. A
I've already tried rebuilding my entire project from scratch as I initially thought it was a directory problem, but having meticulously done this and making thoroughly sure I haven't misplaced a file, I can't see how it would be because of this.
Date.h
#pragma once
#ifndef DATE_H
#define DATE_H
class Date
{
public:
Date(int y, int m, int d);
Date();
const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int yearsDifference();
int daysDifference();
int totalDays();
private:
int year;
int month;
int day;
};
#endif
Date.cpp
#ifndef DATE_H
#define DATE_H
#include <Date.h>
#include <iostream>
#include <string>
Date::Date(int y, int m, int d)
{
y = year;
m = month;
d = day;
}
Date::Date()
{
year = 0;
month = 0;
day = 0;
}
static Date today() {
struct tm ti;
time_t t = time(0);
localtime_s(&ti, &t);
int y = 1900 + ti.tm_year;
int m = 1 + ti.tm_mon;
int d = ti.tm_mday;
return Date(y, m, d);
}
int Date::yearsDifference()
{
bool laterInYear = (month > today().month)
|| (month == today().month && day > today().day);
int result = year - today().year;
if (!laterInYear)
{
result--;
}
return result;
}
int Date::daysDifference()
{
int todayMonthDays = 0;
int maturityMonthDays = 0;
for (int i = 0; i < (month - 1); i++) {
maturityMonthDays += monthDays[i];
}
for (int i = 0; i < (today().month - 1); i++) {
todayMonthDays += monthDays[i];
}
maturityMonthDays += day;
todayMonthDays += today().day;
bool laterInYear = (month > today().month)
|| (month == today().month && day > today().day);
int result;
if (laterInYear)
{
result = maturityMonthDays - todayMonthDays;
}
else
{
result = 365 - (todayMonthDays - maturityMonthDays);
}
return result;
}
int Date::totalDays()
{
int result = (yearsDifference() * 365)
+ daysDifference();
return result;
}
#endif
Any help would be greatly appreciated, I've been staring at this for hours trying to fix it and I just can't see it.
You have to remove the #ifdef guard in the .cpp file.
That is because #include works by copy-n-pasting the entire header file. And because you define DATE_H before you include the Date.h header, DATE_H is also defined in Date.h (which then effectively disables the enitre header).
The Data class constructor should be like this
Date::Date(int y, int m, int d):
year(y),
month(m),
day(d)
{}
Also remove #ifdef's in the cpp files
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;
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.