So I have made a simple class, Newplayer where you can set the name and get the name. Code works when the class is in one cpp file, but as soon as I split the class into an .h and .cpp file I get compiler error which says is unreference.
Text_adventure/main.cpp:14: undefined reference to `Newplayer::setName(std::string)'
In the player.h
#pragma once
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
class Newplayer
{
private:
std::string m_name;
public:
void setName(std::string cName);
std::string getName();
};
int the player.cpp
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "player.h"
void Newplayer::setName(std::string cName)
{
m_name = cName;
}
std::string Newplayer::getName()
{
return m_name;
}
The main file
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "player.h"
int main()
{
// check if a file exist
//load file xor exit
Newplayer player1;
player1.setName("Stackoverflow");
return 0;
}
I don't understand why I am getting an error to string type; everything works when I make a single main.cpp file containing all the files, no warnings.
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
class Newplayer
{
std::string m_name;
public:
void setName(std::string cName)
{
m_name = cName;
}
std::string getName()
{
return m_name;
}
};
int main()
{
Newplayer player1;
player1.setName("Stackoverflow");
printf("Your name is : %s \n", player1.getName().c_str());
return 0;
}
COMPILER INFO
I am running this compiler as of now, I saw that there were some issues with GCC 5, but I don't think I am running GCC 5, or maybe I am, I am clueless on this.
(base) Ivan@ivan-ThinkPad-T490:/usr/bin$ dpkg --list | grep compiler
ii g++ 4:9.3.0-1ubuntu2 amd64 GNU C++ compiler
ii g++-9 9.3.0-17ubuntu1~20.04 amd64 GNU C++ compiler
ii gcc 4:9.3.0-1ubuntu2 amd64 GNU C compiler
ii gcc-9 9.3.0-17ubuntu1~20.04
Aucun commentaire:
Enregistrer un commentaire