First of all this might be messy, because I'm pretty new to programming in general.
Well I'm making a rpg game and I want all my weapons to be in a file called Weapons.cpp.
I made it so that I got all of my global variables such as "weaponDamage" and "weaponName" in a header file called common.h so that I can access and manipulate those variables from both my main and my .cpp file. But the problem is that it can't seem to find those variables and functions in my header.
Here's some code:
common.h:
#include <string>
#ifndef COMMON_H_INCLUDED
#define COMMON_H_INCLUDED
//global variables
extern int pureDamage = 0;
extern int pureHealth = 0;
extern int weaponDamage;
extern int armorDefense;
extern int totalDamage = pureDamage + weaponDamage;
extern int totalHealth = pureHealth + armorDefense;
extern int totalLuck;
extern string starsign;
extern string weaponName;
//all weapons
void weaponSwordIron();
void weaponSwordGold();
void weaponSwordSwordOfTheHeavens();
void weaponBowSimple();
void weaponBowLongBow();
void weaponBowThunder();
void weaponStaffStaffOfFlames();
void weaponStaffStaffOfLightning();
void weaponStaffStaffOfAssKicking();
#endif // COMMON_H_INCLUDED
Weapons.cpp:
#include <iostream>
#include <string>
#include <common.h>
using namespace std;
void weaponSwordIron()
{
int weaponDamage = 5;
string weaponName = "Iron Sword";
}
void weaponSwordGold()
{
int weaponDamage = 8;
string weaponName = "Gold Sword";
}
void weaponSwordSwordOfTheHeavens()
{
int weaponDamage = 15;
string weaponName = "Sword Of The Heavens";
}
void weaponBowSimple()
{
int weaponDamage = 5;
string weaponName = "Simple Bow";
}
void weaponBowLongBow()
{
int weaponDamage = 8;
string weaponName = "Long Bow";
}
void weaponBowThunder()
{
int weaponDamage = 15;
string weaponName = "Thunder Bow";
}
void weaponStaffStaffOfFlames()
{
int weaponDamage = 5;
string weaponName = "Staff Of Flames";
}
void weaponStaffStaffOfLightning()
{
int weaponDamage = 8;
string weaponName = "Staff Of Lightning";
}
void weaponStaffStaffOfAssKicking()
{
int weaponDamage = 15;
string weaponName = "Staff Of Ass Kicking";
}
and a little piece of my main, the function called GiveWeapon():
void GiveWeapon()
{
system("cls");
if (starsign == "mage")
{
weaponSwordIron();
cout << weaponDamage;
cout << weaponName;
}
else if (starsign == "warrior")
{
weaponBowSimple();
}
else if (starsign == "archer")
{
weaponStaffStaffOfFlames();
}
else
{
ChooseStarsign();
}
AssignAttributes();
}
And yes I did remember to include common.h
Now the error my IDE Code::Blocks comes up with is : error: common.h: no such file or directory
I don't know why it comes up with that so please help.
Sorry for the long post and thanks in advance.
Use "common.h" instead of <common.h>.
The angled ones are for library files.
You should use "common.h" not < common.h>
weopens.cpp is mostly non-sense.
i tried compiling the following:
void a() {
int b = 5; }
int main()
{
a();
return 0;
}
and g++ didn't like the idea.
Where is your "common.h" placed? You must specify relative path to them from folder with the "Weapons.cpp".
At second, you define local variables in your functions. Your Weapons.cpp file must look like:
#include <iostream>
#include <string>
#include "relative/path/to/common.h"
//global variables
int pureDamage = 0;
int pureHealth = 0;
int weaponDamage;
int armorDefense;
int totalDamage = pureDamage + weaponDamage;
int totalHealth = pureHealth + armorDefense;
int totalLuck;
string starsign;
string weaponName;
using namespace std;
void weaponSwordIron()
{
weaponDamage = 5;
weaponName = "Iron Sword";
}
void weaponSwordGold()
{
weaponDamage = 8;
weaponName = "Gold Sword";
}
...
In addition to the header location issues and local variable shadowing that others have mentioned, I think you're also going to run into problems with multiple definition errors:
extern int pureDamage = 0;
The initializer on this declaration overrides the extern, so this variable will be not only declared but also defined in any compilation unit that includes this header. Your linker will complain.
When you really want to use globals across multiple files you'll need to define and initialize the variable once in a source file and declare it extern (with no initializer) in the header file. const variables are an exception to this, however.
Related
Is there a way to have a static variable have multiple copies in C/C++?
The following code have a static variable - miles. How to achieve that runner1() and runner2() have its own miles copy but keep miles as static?
test.h
static int miles;
extern int get_miles();
test.c
#include "test.h"
int get_miles() {
miles = miles + 1;
return miles;
}
user.c
#include <stdio.h>
#include "test.h"
extern void runner1();
extern void runner2();
void runner1() {
int i;
for(i=0;i<5;i++) {
printf("runner1 runs %0d miles\n", get_miles());
}
}
void runner2() {
int j;
for(j=0;j<5;j++) {
printf("runner2 runs %0d miles\n", get_miles());
}
}
int main() {
runner1();
runner2();
}
https://www.edaplayground.com/x/3G7h
This is contradictory: You want two things that are different and equal at the same time.
After reading StackOverflow's discussions and implementing some advices, I have these pieces of code intended just to test the behavior of static members of a class.
Here is the header, which has the class declaration:
class OurClass
{
private:
static int x, y;
public:
static void setVals(int valx, int valy);
static int getValx();
static int getValy();
static void initialize();
};
And here is the cpp file, which has the definition of these members as well as the main() function:
#include <iostream>
#include "OurClass.hpp"
using namespace std;
void OurClass::initialize()
{
static int x = 0;
static int y = 0;
}
void OurClass::setVals(int valx, int valy)
{
static int x = valx;
static int y = valy;
}
int OurClass::getValx()
{
static int x;
return x;
}
int OurClass::getValy()
{
static int y;
return y;
}
int main(void)
{
OurClass::inicializa();
cout << "Provide x and y..." << endl;
OurClass::setVals(cin.get(), cin.get());
cout << "Value of x: " << OurClass::getValx() << endl;
cout << "Value of y: " << OurClass::getValy() << endl;
return 0;
}
So, assuming that a static variable exists for the class, and that static functions only access static variables, I was expecting that x and y would have the values that we read from the keyboard with the setVals() call in main(). But when printing their values in the couts, they still have the value we assigned in the initialize() function (which BTW was another suggestion I got here, that is, initialize a static variable in a method).
I am also unable to refer directly to the variables by OurClass::x or y even if I make them public.
Do you guys know why?
First you need to access your local class's static variable instead declaring new method local variables in each method. Check below.
class Out {
private:
static int x, y;
public:
void set(int x, int y);
int getSum();
};
int Out::x = 0;
int Out::y = 0;
void Out::set(int x, int y) {
Out::x = x;
Out::y = y;
}
int Out::getSum() {
return Out::x + Out::y;
}
Instead of setting values of existing variables this code creates new local static variables. Fix:
void OurClass::initialize()
{
x = 0;
y = 0;
}
void OurClass::setVals(int valx, int valy)
{
x = valx;
y = valy;
}
int OurClass::getValx()
{
return x;
}
int OurClass::getValy()
{
return y;
}
And add the definitions of those static variables in a .cc file (not header):
int OurClass::x;
int OurClass::y;
I'm trying to make an Arduino library, for a build that I'm going to be using throughout a few sketches, and I haven't been able to figure out why I keep getting this error. Searching on multiple forums, comes up with no working answers. This is my code:
charLCD.h:
#ifndef charLCD
#define charLCD
#include "Arduino.h"
class charLCD
{
public:
charLCD(int pin1,int pin2,int pin3,int pin4,int enable);
void sendChar(unsigned char c);
private:
int _pin1;
int _pin2;
int _pin3;
int _pin4;
int _enable;
};
#endif
charLCD.cpp:
#include "Arduino.h"
#include "charLCD.h"
#include <limits.h>
charLCD::charLCD(int pin1,int pin2,int pin3,int pin4,int enable) {
_pin1 = pin1;
_pin2 = pin2;
_pin3 = pin3;
_pin4 = pin4;
_enable = enable;
}
void sendChar(unsigned char c) {
// Send char to item
}
char* chartobin ( unsigned char c )
{
static char bin[CHAR_BIT + 1] = {0};
int i;
for ( i = CHAR_BIT - 1; i >= 0; i-- )
{
bin[i] = (c % 2) + '0';
c = c/2;
}
return bin;
}
The problem is on the line where I define the constructor in the header.
Because of
#define charLCD
this is what your compiler sees:
class
{
public:
(int pin1,int pin2,int pin3,int pin4,int enable);
void sendChar(unsigned char c);
private:
int _pin1;
int _pin2;
int _pin3;
int _pin4;
int _enable
};
::(int pin1,int pin2,int pin3,int pin4,int enable) {
_pin1 = pin1;
_pin2 = pin2;
_pin3 = pin3;
_pin4 = pin4;
_enable = enable;
}
// ...
Pick a better header guard.
You also need to qualify the definitions of member functions:
void charLCD::sendChar(unsigned char c) {
// Send char to item
}
I have the following code:
//test.cpp
#include <Physical_file.h>
#include <boost\python.hpp>
using namespace boost::python;
using namespace FMS_Physical;
BOOST_PYTHON_MODULE(python_bridge)
{
class_<Physical_file>("pf")
.def("pcreate", &Physical_file::pcreate)
;
}
//physical_file.h
#include <fstream>
#include "tools.h"
using namespace std;
#define FMS_lvl0_DLL_API __declspec(dllexport)
namespace FMS_Physical
{
const int BLOCK_OFFSET = 20 + 4;
const string SUFFIX(".hash");
struct block
{
unsigned int BlockNr;
char filler[20];
char data[1024 - BLOCK_OFFSET];
};
class Physical_file
{
public:
fstream filefl;
string workingDir;
string fileName;
int fileSize;
block currBlock;
block FHBuffer;
bool opened;
string openMode;
/************
functions
************/
FMS_lvl0_DLL_API Physical_file(void);
FMS_lvl0_DLL_API Physical_file(string &FileName, int FileSize, string &Dir = getCurrentPath());
FMS_lvl0_DLL_API Physical_file(string &FileName, string &Type, string &Dir = getCurrentPath());
FMS_lvl0_DLL_API ~Physical_file(void);
void FMS_lvl0_DLL_API pcreate(string &Name, int Size = 1000, string &Dir = getCurrentPath());
void FMS_lvl0_DLL_API pdelete(void);
void FMS_lvl0_DLL_API popen(string &name, string &OpenMode = string("I"), string &Dir = getCurrentPath());
void FMS_lvl0_DLL_API pclose(void);
void FMS_lvl0_DLL_API seekToBlock(unsigned int BlockNr);
void FMS_lvl0_DLL_API WriteBlock(void);
void FMS_lvl0_DLL_API ReadBlock(void);
void FMS_lvl0_DLL_API WriteFH(void);
void FMS_lvl0_DLL_API ReadFH(void);
};
}
//physical_file.cpp
void Physical_file::pcreate(string &Name, int Size, string &Dir)
{
if (Dir.compare("") == 0)
Dir = getCurrentPath();
string fileFullName = Dir + '\\' + Name + SUFFIX;
this->filefl.open(fileFullName.c_str(),ios::in | ios::binary);
if (filefl.is_open())
{
throw new exception((string("in function Physical_file::pcreate, file:") + fileFullName + " exists.").c_str());
}
try{
this->filefl.open(fileFullName.c_str(),ios::binary | ios::out);
this->opened = true;
this->seekToBlock(0);
this->currBlock.BlockNr = 0;
for (int i = 0; i < Size; i++)
{
for (int j = 0; j < sizeof(currBlock.data); j++)
this->currBlock.data[j] = 0;
for (int j = 0; j < sizeof(currBlock.filler); j++)
this->currBlock.filler[j] = 0;
this->WriteBlock();
}
this->pclose();
this->fileName = Name;
this->workingDir = Dir;
this->fileSize = Size;
}
catch(exception e)
{
throw new exception("in Physical_file::pcreate \n" + *e.what());
}
}
Physical_file::Physical_file(void)
{
this->fileName = string("");
this->workingDir = string("");
this->opened = false;
}
(there is some more code, I think its irrelevant to the problem)
when trying to compile I get the following error:
error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'
can anyone explain why this problem happens and how to fix it?
(I'm compiling using vs2010, python27 and the c++ boost libs)
the files physical_file.cpp and physical_file.h are compiled to a dll used by test.cpp
By default, Boost.Python will automatically register to_python conversions for exposed types, such as Physical_file. As such, Boost.Python requires that these types be copyable. In this case, Physical_file is not copyable its filefl members is of a type that is not copyable: fstream.
To resolve this, either:
Determine copy/ownership semantics of filefl, and manage it through a holder object. For example, boost::shared_ptr.
Suppress automatic registration of python conversions by providing boost::noncopyable as a template argument when exposing the Physical_file class.
BOOST_PYTHON_MODULE(python_bridge)
{
boost::python::class_<Physical_file, boost::noncopyable>("pf")
.def("pcreate", &Physical_file::pcreate)
;
}
For more options when exposing a C++ class to Python, refer to the boost::python::class_ documentation.
I have the following class and corresponding header file:
#ifndef ORDER_H_
#define ORDER_H_
#include "Side.h"
using namespace std;
class Order {
public:
int _id;
Side _side;
int _ackedPrc;
int _ackedQty;
int _requestedPrc;
int _requestedQty;
int _filledQty;
Order(){
_id = -1;
_side = BID;
_ackedPrc = -1;
_ackedQty = 0;
_requestedPrc = 0;
_requestedQty = 0;
_filledQty = 0;
}
void cancel(){
_requestedQty = 0;
}
void amend(int prc, int qty){
_requestedPrc = prc;
_requestedQty = qty;
}
void amended(){
_ackedPrc = _requestedPrc;
_ackedQty = _requestedQty;
}
void acked(){
amended();
}
void onFill(int fillQty){
_filledQty += fillQty;
}
int filledQty(){
return _filledQty;
}
int prc(){
return _requestedQty;
}
int remainingQty(){
return _requestedQty - _filledQty;
}
int id(){
return _id;
}
Side side(){
return _side;
}
bool pendingMod(){
return _ackedPrc != _requestedPrc || _ackedQty != _requestedQty;
}
};
#endif
#ifndef ORDER_H_
#define ORDER_H_
#include "Side.h"
class Order {
public:
int _id;
Side _side;
int _ackedPrc;
int _ackedQty;
int _requestedPrc;
int _requestedQty;
int _filledQty;
Order();
void cancel();
void amend(int prc, int qty);
void amended();
void acked();
void onFill(int fillQty);
int filledQty();
int prc();
int remainingQty();
int id();
Side side();
bool pendingMod();
};
#endif /* ORDER_H_ */
When I try to instantiate this object, I get the symbol(s) not found error in CDT/Eclipse on my Mac. However, I can easily instantiate any other class in the project, so I'm pretty sure my problem lies with the Order class:
int main() {
Order o;//This gives me an error
// OrderBook ob; But this works
// QuoteBook qb; And this works
return 0;
}
Can anyone spot my problem? I keep thinking that somewhere my declaration doesn't match my definition somewhere, but I don't see how. (And yes, I'm a C++ newb. Pardon any best-practices violations.)
Thanks
A Java programmer by any chance? By the look of your code, you've actually declared the Order class twice. In C++ you usually declare a class and then you define the member variables and functions in it. Actually, you can declare and define in one like your first declaration of Order, but it's not normally good practice unless the code is very brief. In any case I'd suggest that your header should look like this:
#ifndef ORDER_H_
#define ORDER_H_
#include "Side.h"
class Order {
public:
int _id;
Side _side;
int _ackedPrc;
int _ackedQty;
int _requestedPrc;
int _requestedQty;
int _filledQty;
Order();
void cancel();
void amend(int prc, int qty);
void amended();
void acked();
void onFill(int fillQty);
int filledQty();
int prc();
int remainingQty();
int id();
Side side();
bool pendingMod();
};
#endif /* ORDER_H_ */
This still has the include guards in so it'll only be included once in any compilation unit. Now your cpp file (with the definitions in it) shoudl probably look something like this:
#include <Order.hpp>
Order::Order(){
_id = -1;
_side = BID;
_ackedPrc = -1;
_ackedQty = 0;
_requestedPrc = 0;
_requestedQty = 0;
_filledQty = 0;
}
void Order::cancel(){
_requestedQty = 0;
}
void Order::amend(int prc, int qty){
_requestedPrc = prc;
_requestedQty = qty;
}
void Order::amended(){
_ackedPrc = _requestedPrc;
_ackedQty = _requestedQty;
}
void Order::acked(){
amended();
}
void Order::onFill(int fillQty){
_filledQty += fillQty;
}
int Order::filledQty(){
return _filledQty;
}
int Order::prc(){
return _requestedQty;
}
int Order::remainingQty(){
return _requestedQty - _filledQty;
}
int Order::id(){
return _id;
}
Side Order::side(){
return _side;
}
bool Order::pendingMod(){
return _ackedPrc != _requestedPrc || _ackedQty != _requestedQty;
}
Please note that I've clearly not tested this at all. The main thing to note is that here are the bodies of your Order class functions. Notice that the names have to be scoped within the Order class. Hope this helps.