LNK 2019: Unresolved External Symbol in VS 2017 and Code Correction - lnk2019

This is my code, I am facing problem while build and run.
LNK 2019 Unresolved external symbol error it is.
Please help me to solve this problem.
Person.h
#pragma once
#include<string>
class Person
{
private:
std::string firstname;
std::string lastname;
int age;
public:
Person();
Person(std::string fname, std::string lname);
Person(std::string fname, std::string lname, int age);
~Person();
void setfirstname(std::string fname);
std::string getfirstname();
void setlastname(std::string lname);
std::string getlastname();
void setage(int age);
int getage();
void sayhello();
};
Person.cpp
#include "Person.h"
#include"stdafx.h"
#include<iostream>
Person::Person()
{
firstname = "";
lastname = "";
age = 0;
}
Person::Person(std::string fname, std::string lname)
{
firstname = fname;
lastname = lname;
}
Person::Person(std::string fname, std::string lname, int age)
{
firstname = fname;
lastname = lname;
this->age = age;
}
Person::~Person()
{
}
void Person::setfirstname(std::string fname)
{
this->firstname = fname;
}
void Person::setlastname(std::string lname)
{
this->lastname = lname;
}
void Person::setage(int age)
{
if (age > 0)
{
this->age = age;
}
else
{
std::cout << "Plz Enter a valid age" << std::endl;
}
}
std::string Person::getfirstname()
{
return this->firstname;
}
std::string Person::getlastname()
{
return this->lastname;
}
int Person::getage()
{
return this->age;
}
void Person::sayhello()
{
std::cout << "Hello" << std::endl;
}
Main Function
#include "stdafx.h"
#include<iostream>
#include"Person.h"
int main()
{
Person *p = new Person("Barry", "Allen", 30);
std::cout << "The name of Person is" << p->getfirstname() << " " <<
p>getlastname() << " And the age is" << p->getage() << std::endl;
p->sayhello();
return 0;
}
The message I am getting is :
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: __thiscall
Person::Person(class std::basic_string,class std::allocator >,class
std::basic_string,class
std::allocator >,int)"
(??0Person##QAE#V?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##0H#Z)
referenced in function
_main ConsoleApplication2 C:\Users\Subhajyoti-PC\source\repos\ConsoleApplication2\ConsoleApplication2\ConsoleApplication2.obj 1

Related

Forwarding rvalue into a thread where it is further forwarded to another function

I'm trying to create a deadline class which starts a thread in its constructor. Once the deadline (a time priod) occur within a thread, a function provided as argument should be executed.
The class'es contructor takes that function as a parameter, as well as arguments of that function.
I can provide parameter by value and by reference, but when providing rvalue as parameter, I get compile error, which I don't know how to solve.
#include <thread>
#include <atomic>
#include <future>
#include <iostream>
#include <iomanip>
namespace {
std::atomic<bool> running{true};
template <typename Period>
using duration = std::chrono::duration<int64_t, Period>;
template <typename PromiseType = void>
class deadline {
std::promise<PromiseType> stopper_{};
std::thread thread_{};
public:
deadline() = delete;
template <typename Period, typename Function, typename... Args>
explicit deadline(const duration<Period> &interval, Function&& func, Args&&... args) noexcept {
if (interval.count() > 0) {
std::future<PromiseType> future{ stopper_.get_future() };
using tuple = std::tuple<std::decay_t<Args>...>;
auto decay_copied = std::make_unique<tuple>(std::forward<Args>(args)...);
thread_ = std::thread(
[](std::future<PromiseType>&& future,
const duration<Period> &interval,
Function&& func, decltype(decay_copied)&& params) {
if (future.wait_for(interval) == std::future_status::timeout) {
std::apply(func, *params);
}
}, std::move(future), std::cref(interval), std::forward<Function>(func), std::move(decay_copied));
}
}
deadline(const deadline&) = delete;
deadline(deadline&&) = delete;
deadline& operator=(const deadline&) = delete;
deadline& operator=(deadline&&) = delete;
~deadline() {
stopper_.set_value();
if (thread_.joinable()) {
thread_.join();
}
}
};
}
auto main() -> int {
std::string test1{"test 1"};
std::string test2{"test 2"};
std::string test3{"test 3"};
std::string test4{"test 4"};
using namespace std::chrono_literals;
deadline dl(5s,
[](
std::string test_1
, const std::string& test_2
, std::string& test_3
, std::string&& test_4
) {
std::cout << test_1 << '\n';
std::cout << test_2 << '\n';
std::cout << test_3 << '\n';
test_3 += " modified";
std::cout << test_4 << '\n';
running = false;
}
, test1
, std::cref(test2)
, std::ref(test3)
, std::move(test4)
//, "test 4"
);
while (running.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << test1 << '\n';
std::cout << test2 << '\n';
std::cout << test3 << '\n';
std::cout << test4 << '\n';
return 0;
}
The code could be checked here also:
https://godbolt.org/z/fx3a4szoY
Any help is appreciated.
Thanks!
When providing a const value (also a rvalue), it works, it doesn't work if I use std::move.

Incorrect checksum for freed object in c++/sfml application

I am trying to create a multiplayer game where players can use voice chat to communicate.
I am using C++ and SFML-3.0 for everything.
Here is the GitHub page for the whole project: https://github.com/iwannabespace/test
First of all, here are some of the classes that I am using:
AudioCapturer.hpp
class AudioCapturer : public sf::SoundStream
{
public:
AudioCapturer(Client& client);
void receiveLoop(sf::Packet& packet);
private:
bool onGetData(sf::SoundStream::Chunk& data) override;
void onSeek(sf::Time timeOffset) override;
private:
std::recursive_mutex mutex;
std::vector<std::int16_t> samples;
std::vector<std::int16_t> tempbuffer;
size_t offset;
Client& client;
};
AudioCapturer.cpp
AudioCapturer::AudioCapturer(Client& client)
: offset(0), client(client)
{
initialize(1, 44100);
}
bool AudioCapturer::onGetData(sf::SoundStream::Chunk& data)
{
while (offset >= samples.size())
sf::sleep(sf::milliseconds(10));
{
std::scoped_lock lock(mutex);
tempbuffer.assign(samples.begin() + static_cast<std::vector<std::int64_t>::difference_type>(offset),
samples.end());
std::cout << "Tempbuffer address: " << &tempbuffer << std::endl;
}
data.samples = tempbuffer.data();
data.sampleCount = tempbuffer.size();
offset += tempbuffer.size();
return true;
}
void AudioCapturer::onSeek(sf::Time timeOffset)
{
offset = static_cast<std::size_t>(timeOffset.asMilliseconds()) * getSampleRate() * getChannelCount() / 1000;
}
void AudioCapturer::receiveLoop(sf::Packet& packet)
{
while (true)
{
if (client.receivedAudio)
{
sf::Packet copy = packet;
std::uint8_t command;
if (copy >> command)
{
std::size_t sampleCount = (copy.getDataSize() - 1) / sizeof(std::int16_t);
{
std::scoped_lock lock(mutex);
std::size_t oldSize = samples.size();
samples.resize(oldSize + sampleCount);
std::cout << "Samples address: " << &samples << std::endl;
std::cout << "Last item address: " << &samples[oldSize] << std::endl;
std::memcpy(&(samples[oldSize]),
static_cast<const char*>(copy.getData()) + 1,
sampleCount * sizeof(std::int16_t));
}
client.receivedAudio = false;
}
}
}
}
Client.hpp
class Client
{
public:
Client(const sf::IpAddress& ip, int port);
~Client();
bool connect();
void disconnect();
bool send(sf::Packet& packet);
bool receivePacket(sf::Packet& packet, std::unordered_map<std::uint32_t, Player>& players, std::uint32_t& thisPlayer);
public:
bool receivedAudio;
bool receivedPosition;
private:
int port;
sf::IpAddress ip;
sf::TcpSocket socket;
};
Client.cpp
Client::Client(const sf::IpAddress& ip, int port)
: ip(ip), port(port), receivedAudio(false), receivedPosition(false)
{
}
Client::~Client()
{
}
bool Client::connect()
{
if (socket.connect(ip, port) != sf::Socket::Done)
return false;
return true;
}
void Client::disconnect()
{
socket.disconnect();
}
bool Client::send(sf::Packet& packet)
{
if (socket.send(packet) != sf::Socket::Done)
return false;
return true;
}
bool Client::receivePacket(sf::Packet& packet, std::unordered_map<std::uint32_t, Player>& players, std::uint32_t& thisPlayer)
{
sf::Packet recv;
sf::Packet copy;
while (true)
{
if (socket.receive(recv) != sf::Socket::Done)
return false;
if (receivedAudio)
std::cout << "Data is not used!" << std::endl;
std::uint8_t command;
std::uint32_t id;
copy = recv;
if (copy >> command)
{
switch (command)
{
case ServerCommand::ADD_PLAYER:
copy >> id;
if (thisPlayer == 0)
{
thisPlayer = id;
std::cout << "My id is " << thisPlayer << std::endl;
}
players[id] = Player(5.f, id);
std::cout << "Player joined!" << std::endl;
break;
case ServerCommand::ADD_PLAYERS:
while (copy >> id)
players[id] = Player(5.f, id);
break;
case ServerCommand::RECEIVE_AUDIO:
receivedAudio = true;
packet = recv;
break;
case ServerCommand::RECEIVE_POSITION:
receivedPosition = true;
packet = recv;
break;
default:
break;
}
}
}
return true;
}
AudioRecorder.hpp
class AudioRecorder : public sf::SoundRecorder
{
public:
AudioRecorder(Client& client);
~AudioRecorder() override;
void activeness();
void setActive(bool active);
bool isActive() const;
private:
bool onStart() override;
bool onProcessSamples(const std::int16_t* samples, std::size_t sampleCount) override;
void onStop() override;
private:
Client& client;
bool active;
std::mutex mutex;
};
AudioRecorder.cpp
AudioRecorder::AudioRecorder(Client& client)
: client(client), active(false)
{
}
AudioRecorder::~AudioRecorder()
{
stop();
}
void AudioRecorder::activeness()
{
while (true)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !active)
{
std::scoped_lock lock(mutex);
active = true;
if (start()) {}
}
if (!sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && active)
{
std::scoped_lock lock(mutex);
stop();
active = false;
}
}
}
void AudioRecorder::setActive(bool active)
{
this->active = active;
}
bool AudioRecorder::isActive() const
{
return active;
}
bool AudioRecorder::onStart()
{
std::cout << "Started!" << std::endl;
return true;
}
bool AudioRecorder::onProcessSamples(const std::int16_t* samples, std::size_t sampleCount)
{
sf::Packet packet;
packet << ServerCommand::RECEIVE_AUDIO;
packet.append(samples, sampleCount * sizeof(std::int16_t));
return client.send(packet);
}
void AudioRecorder::onStop()
{
std::cout << "Stopped!" << std::endl;
}
main.cpp
int main()
{
std::srand(std::time(0));
Client client("127.0.0.1", 4242);
if (client.connect())
{
std::cout << "Connected to server!" << std::endl;
sf::RenderWindow window(sf::VideoMode({ 1280, 720 }), "Multiplayer Game", sf::Style::Default);
window.setVerticalSyncEnabled(true);
sf::View view;
view.setCenter({ 640, 360 });
view.setSize(sf::Vector2f(window.getSize()));
sf::Packet packet;
std::unordered_map<std::uint32_t, Player> players;
std::uint32_t thisPlayer = 0;
StartScreen startscreen(window, sf::Color(172, 192, 146));
AudioRecorder recorder(client);
AudioCapturer capturer(client);
capturer.play();
std::thread receivePacket;
std::thread receiverloop;
std::thread activeness;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::Resized:
if (startscreen)
{
view.setCenter({
static_cast<float>(window.getSize().x) / 2,
static_cast<float>(window.getSize().y) / 2
});
view.setSize(sf::Vector2f(window.getSize()));
startscreen.updateOnResize();
}
break;
}
}
if (!receivePacket.joinable())
receivePacket = std::thread(&Client::receivePacket, std::ref(client), std::ref(packet), std::ref(players), std::ref(thisPlayer));
if (!receiverloop.joinable())
receiverloop = std::thread(&AudioCapturer::receiveLoop, std::ref(capturer), std::ref(packet));
if (!activeness.joinable())
activeness = std::thread(&AudioRecorder::activeness, std::ref(recorder));
if (client.receivedPosition)
{
sf::Packet copy = packet;
std::uint8_t command;
if (copy >> command)
{
float x, y;
std::uint32_t id;
copy >> id >> x >> y;
for (auto& player : players)
if (player.first == id)
player.second.setPosition({ x, y });
client.receivedPosition = false;
}
}
if (window.hasFocus())
players[thisPlayer].move(client);
window.clear(sf::Color::White);
window.setView(view);
for (const auto& player : players)
window.draw(player.second);
window.display();
}
client.disconnect();
std::terminate();
}
return 0;
}
I know it's a lot of code and I am sorry that I have to share too much.
I believe the problem is with the AudioCapturer class. For some reason when sending audio data, after a while client that receives it stops the execution and prompts this problem with different addresses:
a.out(60911,0x16b47b000) malloc: Incorrect checksum for freed object 0x12a80a400: probably modified after being freed.
Corrupt value: 0xe7026101a000bcff
By the way I am kind of using the SFML's VoIP example for the AudioCapturer class.
This is the Github page of it: https://github.com/SFML/SFML/blob/master/examples/voip/Server.cpp
I'd appreciate it If someone can help me with that problem.

why the "getline" command does not get recognized by VS?

The word "getline" is a red and underlined, which indicate an error:
#include <iostream>
using namespace std;
string ReadName()
{
string Name;
cout << "Please Enter Your Name: " << endl;
getline(cin, Name);
return Name;
}
void PrintName(string Name)
{
cout << "\nYour name is " << Name << endl;
}
int main()
{
PrintName(ReadName());
return 0;
}
The VS Gives an error regarding getline

How would I define move constructor and move assignment operator for unique_ptr of custom data type?

class threadMsg_t {
private:
string msg;
int type;
public:
threadMsg_t(const string& msg, int type) : msg(msg), type(type) {};
threadMsg_t& operator=(threadMsg_t&& oldMsg)
{
msg = move(oldMsg.msg);
type = move(oldMsg.type);
return *this;
}
threadMsg_t(threadMsg_t&& oldMsg) {
msg = move(oldMsg.msg);
type = move(oldMsg.type);
}
int getType() { return type; }
string getMsg() { return msg; }
};
using msgP_t = unique_ptr<threadMsg_t>;
static queue<msgP_t> q;
static condition_variable cv;
static mutex mtx;
static void postMsg(threadMsg_t* newMsg)
{
unique_lock<mutex> lck(mtx);
q.push(std::move(msgP_t{newMsg}));
cv.notify_one();
}
class workerThread_t {
public:
static void processMsg()
{
while(true) {
unique_lock<mutex> lck{mtx};
if(q.empty()) {
cout << "Waiting for the message!" << endl;
cv.wait(lck, []() { return !(q).empty(); });
}
if(q.empty()) {
continue;
}
auto msgP = move(q.front());
threadMsg_t* msg = msgP.get();
q.pop();
cout << "Processed Message - " << msg->getMsg() << endl;
lck.unlock();
}
}
thread* getThread()
{
return m_workerThread;
}
workerThread_t() {
m_workerThread = new thread(&processMsg);
}
~workerThread_t()
{
delete(m_workerThread);
}
private:
thread* m_workerThread;
};
Code works fine. But wondering the behavior when I do move(unique_ptr object) inside postMsg(). Seems like its not invoking the move constructor defined. Not sure whether its possible to define constructor for unique_ptr. I know that its needed for a custom structure containing "string" and "int". How would it behave if I have a ptr inside the structure?

Runnable implementation using packaged_task in c++11

I am trying to create a Runnable interface in c++11 using packaged_task, with child class overriding run() function. I don't know why this code is not compiling. Its giving error related to type argument.
/usr/include/c++/4.8.1/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of()>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
Below is my code snippet. Could someone plz give me some information on this error and whether implementing Runnable this way is a right way to proceed ?
class Runnable {
public:
explicit Runnable() {
task_ = std::packaged_task<int()>(&Runnable::run);
result_ = task_.get_future();
std::cout << "starting task" << std::endl;
}
virtual int run() = 0;
int getResult() {
task_();
return result_.get();
}
virtual ~Runnable() {
std::cout << "~Runnable()" << std::endl;
}
private:
std::future<int> result_;
std::packaged_task<int()> task_;
};
class foo : public Runnable {
int fib(int n) {
if (n < 3) return 1;
else return fib(n-1) + fib(n-2);
}
public:
explicit foo(int n) : n_(n) {}
int run() {
cout << "in foo run() " << endl;
int res = fib(n_);
cout << "done foo run(), res = " << res << endl;
return res;
}
~foo() {}
private:
int n_;
};
int main(int argc, char*argv[]) {
stringstream oss;
oss << argv[1];
int n;
oss >> n;
shared_ptr<foo> obj(new foo(n));
obj->run();
cout << "done main" << endl;
return 0;
}

Resources