Expected unqualified-id before 'int' - c++

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
}

Related

Parsing array in library constructor - Pointer problem (C++)

I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.
It is obviously a pointer problem, but I don't know how to solve it. There are four errors left in my code:
WayPointStack.cpp:23:7: error: incompatible types in assignment of 'WPCommand*' to 'WPCommand [0]'
_wp = new WPCommand[arrSize]; //Fixed
WayPointStack.cpp:44:34: error: could not convert '(operator new(16u), (((WPCommand*)<anonymous>)->WPCommand::WPCommand(4, 10000), ((WPCommand*)<anonymous>)))' from 'WPCommand*' to 'WPCommand'
return new WPCommand(_END, 10000);
WayPointStack.cpp:59:15: error: no match for 'operator=' (operand types are 'WPCommand' and 'WPCommand*')
_wp[pointer] = new WPCommand(target, time); # Fixed
WPCommand.h:10:7: note: candidate: WPCommand& WPCommand::operator=(const WPCommand&)
class WPCommand # Does not appear anymore, fixed
WPCommand.h
#ifndef WPCommand_h
#define WPCommand_h
#include "Arduino.h"
class WPCommand
{
public:
WPCommand(int target, int time );
WPCommand();
int GetTarget();
int GetTime();
int LEFT;
int RIGHT;
int FORWARD;
int BACKWARD;
int STOP;
int END;
private:
int _target;
int _time;
};
#endif
WayPointStack.h
#ifndef WayPointStack_h
#define WayPointStack_h
#include "Arduino.h"
#include "WPCommand.h"
class WayPointStack
{
public:
WayPointStack();
WayPointStack(WPCommand wp[], int length);
WPCommand GetNextWP();
WPCommand GetWP(int i);
void AddWP(int target, int time);
int SetWPPointer(int i);
int GetWPPointer();
int GetLength();
private:
WPCommand _wp[];
int pointer;
int _length;
};
#endif
WayPointStack.cpp (partly)
#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"
#define _BACKWARD 0
#define _FORWARD 1
#define _STOP 2
#define _LEFT 3
#define _RIGHT 4
#define _END 4
#define arrSize 100
WayPointStack::WayPointStack()
{
_wp = new WPCommand[arrSize];
_length = 0;
pointer = 0;
}
WayPointStack::WayPointStack(WPCommand wp[], int length)
{
_wp = new WPCommand[arrSize];
for (int i = 0; i < length; i++){
_wp[i] = wp[i];
}
_length = length;
pointer = 0;
}
WPCommand WayPointStack::GetNextWP()
{
if (pointer < _length){
pointer++;
return _wp[pointer-1];
}
return new WPCommand(_END, 10000);
}
I tried to more or less randomly reference and derefence _wp and wp[] but it did not work.
Edit:
Changing
WPCommand _wp[];
to
WPCommand *_wp;
successfully fixed the first error. Doing the same to
WayPointStack(WPCommand *wp, int length);
Edit:
_wp[pointer] = WPCommand(target, time);
instead of
_wp[pointer] = new WPCommand(target, time);
successfully fixed error number 3.
Edit:
return WPCommand(_END, 10000);
fixed error number 2.
Problem solved.

How to fix Segmentation Fault error when instantiating objects

I'm working to create a few classes that work together to simulate functions for a rental car agency. I have the classes working and I can create objects of each of the classes, but when I try to run the following code I get a segmentation fault and I'm not sure why. Why am I getting a segmentation fault when I declare the objects in this order?
I've tried switching the order in which I declare the objects and the error goes away. If I declare two cars with just the Car() constructor, then the problem also goes away. If I remove any of the functions in either the Car or Sensor class, the error goes away.
PS: I asked this question a few days ago, and I included way too much code because I couldn't identify the error (far from complete, minimal, and verifiable), but this time I've narrowed it down as far as I can. I apologize if it's a lot of code, but I've removed all the code I can and if I remove any more of it the problem goes away.
Here's my main file:
#include "Car.h"
int main() {
char make[] = "Subaru", model[] = "Outback", name[] = "Brandon",
type[] = "radar";
Sensor sensors[3];
Sensor sensor1 = Sensor(type), sensor2 = Sensor(), sensor3 =
Sensor();
sensors[0] = sensor1;
sensors[1] = sensor2;
sensors[2]= sensor3;
Car car1 = Car();
Car car2 = Car(make, 155.81, sensors);
return 0;
}
My Car class:
#ifndef CAR_H
#define CAR_H
#include <iostream>
#include "MyString.h"
#include "Sensor.h"
using namespace std;
#define MAX_STR_SIZE 256
#define MAX_NUM_SNSRS 3
class Car {
public:
Car();
Car(char* make, float baseprice, Sensor* sensors);
void setMake(char* make);
void setBaseprice(float baseprice);
void setAvailable(bool available);
void setOwner(char* owner);
void updatePrice();
private:
char m_make[MAX_STR_SIZE];
Sensor m_sensors[MAX_NUM_SNSRS];
int m_numsensors;
float m_baseprice;
float m_finalprice;
bool m_available;
char m_owner[MAX_STR_SIZE];
};
#endif
#include "Car.h"
Car::Car() {
char dflt[] = {'\0'};
setMake(dflt);
setAvailable(true);
setOwner(dflt);
m_numsensors = 0;
setBaseprice(0.0);
}
Car::Car(char* make, float baseprice, Sensor* sensors) {
char dflt[] = {'\0'};
setMake(make);
setAvailable(true);
setOwner(dflt);
for(int i = 0; i < MAX_NUM_SNSRS; i++) {
(*(m_sensors + i)) = Sensor(*(sensors + i));
if(myStringCompare((sensors + i)->getType(), "none") != 0) {
m_numsensors++;
}
}
setBaseprice(baseprice);
}
void Car::setMake(char* make) {
myStringCopy(m_make, make);
}
void Car::setBaseprice(float baseprice) {
m_baseprice = baseprice;
updatePrice();
}
void Car::setAvailable(bool available) {
m_available = available;
}
void Car::setOwner(char* owner) {
myStringCopy(m_owner, owner);
}
void Car::updatePrice() {
float totSnsrPrice = 0.0;
for(int i = 0; i < m_numsensors; i++) {
totSnsrPrice += (m_sensors + i)->getCost();
}
m_finalprice = m_baseprice + totSnsrPrice;
}
My Sensor class:
#ifndef SENSOR_H
#define SENSOR_H
#include "MyString.h"
#define MAX_STR_SIZE 256
#define NUM_TYPES 5
class Sensor {
public:
Sensor();
Sensor(char* type);
char* getType();
float getCost();
void setType(char* type);
void setCost(float extraCost);
private:
char m_type[MAX_STR_SIZE];
float m_extracost;
};
#endif
#include "Sensor.h"
const char* validSensors[] = {"gps", "camera", "lidar", "radar",
"none"};
const float prices[] = {5.0, 10.0, 15.0, 20.0, 0.0};
Sensor::Sensor() {
char dflt[] = "none";
setType(dflt);
setCost(0.0);
}
Sensor::Sensor(char* type) {
int index = -1;
char dflt[] = "none";
for(int i = 0; i < NUM_TYPES; i++) {
if(myStringCompare(type, *(validSensors + i)) == 0) {
index = i;
}
}
if(index < 0) {
setType(dflt);
setCost(0.0);
} else {
setType(type);
setCost(*(prices + index));
}
}
char* Sensor::getType() {
return m_type;
}
float Sensor::getCost() {
return m_extracost;
}
void Sensor::setType(char* type) {
myStringCopy(m_type, type);
}
void Sensor::setCost(float extracost) {
m_extracost = extracost;
}
myStringCopy and myStringCompare are just the typical std::string copy and compare functions, we're just not allowed to use them (they are include in MyString.h, I've been using them for a while, so I know they work as intended).
I expect the output to be nothing, but still successful, instead of a segmentation fault. I cannot find the error anywhere, any help would be appreciated. Thanks!
Edit: Here's my string class, as asked:
#ifndef MYSTRING_H
#define MYSTRING_H
int myStringCompare(const char* str1, const char* str2);
char* myStringCopy(char* destination, const char* source);
#endif
#include "MyString.h"
int myStringCompare(const char* str1, const char* str2) {
int index = 0;
while(*(str1 + index) != '\0' || *(str2 + index) != '\0') {
if(*(str1 + index) < *(str2 + index)) {
return -1;
}
if(*(str1 + index) > *(str2 + index)) {
return 1;
}
index++;
}
return 0;
}
char* myStringCopy(char* destination, const char* source) {
int index = 0;
while(*(source + index) != '\0') {
*(destination + index) = *(source + index);
index++;
}
*(destination + index) = '\0';
return destination;
}
We don't have the full details on your string class, so this is hard to reproduce.
However, when you call sensors[0] = sensor1; you are copying your Sensor, but haven't defined an assignment operator (or copy constructor for that matter).
You also do this in the Car constructor with
(*(m_sensors + i)) = Sensor(*(sensors + i));
Now without the full details of your string class, I can give suggestions that might help.
First, you are doing a lot of copying when you set up the senors.
You can collapse this
Sensor sensors[3];
Sensor sensor1 = Sensor(type), sensor2 = Sensor(), sensor3 =
Sensor();
sensors[0] = sensor1;
sensors[1] = sensor2;
sensors[2]= sensor3;
down to
Sensor sensors[3]={{type}, {}, {}};
This might not solve the problem, but is less to look at.
Next, remove the setters. You can use delegating constructors to tie the two you have together, and avoid these.
This avoids some copies.
Look very carefully at what gets deep or shallow copied.
If you have two char * types,
char * word = "Hello";
char * another_word = word;
the second is a "shallow" copy. You need an equivalent of strcpy to actually make a different ("deep") copy of the string.

Integrating an old C++ code into a PNaCl module

I read Google’s native client tutorial on how to build my own C++ based PNaCl module several times and somehow I'm not getting wiser, I know that if I want to implement a messaging functionality. I have the following in the .cc file as basis for a PNaCl code, all this is taken from Googles's Hello World tutorial:
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/cpp/var.h"
namespace {
// The expected string sent by the browser.
const char* const kHelloString = "hello";
// The string sent back to the browser upon receipt of a message
// containing "hello".
const char* const kReplyString = "hello from NaCl";
} // namespace
class job1Instance : public pp::Instance {
public:
explicit job1Instance(PP_Instance instance): pp::Instance(instance) {}
virtual ~job1Instance() {}
virtual void HandleMessage(const pp::Var& message) {
if (!message.is_string()) {
return;
}
std::string message_txt = message.AsString();
pp::Var reply;
if (message_txt == kHelloString) {
reply = pp::Var(kReplyString);
PostMessage(kReplyString);
}
}
};
class job1 : public pp::Module {
public:
job1() : pp::Module() {}
virtual ~job1() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new job1Instance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new job1();
}
} // namespace pp
As I understand the PNaCl modules don’t use a main() function and yet let’s say I have an old C++ code that creates 2 arrays unsorted1 and unsorted2 with random numbers which I want to use in my PNaCl module:
#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <array>
// a function to create a random number between min and max
int32_t rangeRandomAlg (int32_t min, int32_t max) {
int32_t num = max - min + 1;
int32_t remainder = RAND_MAX % num;
int32_t x;
do {
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % num;
}
// a function to create arrays with random numbers
void unsortedArrays(int32_t unsorted1[], int32_t unsorted2[],int32_t arrayElements, int32_t minNum, int32_t maxNum){
for(int32_t i = 0; i <= arrayElements; i++) {
if (i < arrayElements/2) {
unsorted1[i] = rangeRandomAlg(minNum, maxNum);
} else {
unsorted2[i] = rangeRandomAlg(minNum, maxNum);
}
}
}
// the main function
int32_t main(int32_t argc, char *argv[]) {
// declare all the zises
int32_t minNum = 0;
int32_t maxNum = 100;
int32_t arrayElements = maxNum;
// the arrays
int32_t unsorted1[arrayElements/2];
int32_t unsorted2[arrayElements/2];
// fill the arrays with random numbers
unsortedArrays(unsorted1, unsorted2, arrayElements, minNum, maxNum);
return 0;
}
My problem is that I didn’t quite understand how can I integrate this code into the PNaCl module and use the HandleMessage() function to sent the unsorted1 and unsorted2 arrays back to the JavaScript with the PostMesage() function. I know I have to work with arrays and not strings in the HandleMessage() function.
I hope to get some help here, since I’m really new to this whole native client thing.
Well here is the solution that took some hours to get to:
// pepper includes
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var_array.h"
#include "ppapi/cpp/var.h"
#include "json/json.h"
#include <sstream>
// cpp includes
#include <stdint.h>
#include <unistd.h>
#include <array>
#include <string>
//static variables
namespace {
// The expected string sent by the browser.
const char* const kHelloString = "Bereit fuer dein Modul";
// The string sent back to the browser upon receipt of a message
// containing "hello".
const char* const kReplyString = "PNaCl hat Ergebnisse geschickt";
} // namespace
class job1Instance : public pp::Instance {
public:
explicit job1Instance(PP_Instance instance): pp::Instance(instance) {}
virtual ~job1Instance() {}
virtual void HandleMessage(const pp::Var& message) {
/*
if (!message.is_string()) {
return;
}
std::string message_txt = message.AsString();
pp::Var reply;
if (message_txt == kHelloString) {
reply = pp::Var(kReplyString);
PostMessage(kReplyString);
}
*/
/*** my functions and data for the cpp code to integrate start here ***/
// declare all the zises
int32_t minNum = 0;
int32_t maxNum = 100;
int32_t arrayElements = maxNum;
// the arrays
int32_t unsorted1[arrayElements/2];
int32_t unsorted2[arrayElements/2];
// fill the arrays with random numbers
unsortedArrays(unsorted1, unsorted2, arrayElements, minNum, maxNum);
std::string outRes1, outRes2;
arrayToString(unsorted1, arrayElements/2, outRes1);
arrayToString(unsorted2, arrayElements/2, outRes2);
PostMessage(outRes1); // send the unsorted1 array as a string to the JavaScript back
}
private:
// function to create a random number between min and max
int32_t rangeRandomAlg (int32_t min, int32_t max) {
int32_t num = max - min + 1;
int32_t remainder = RAND_MAX % num;
int32_t x;
do {
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % num;
}
// function to create arrays with random numbers
void unsortedArrays (int32_t unsorted1[], int32_t unsorted2[],int32_t arrayElements, int32_t minNum, int32_t maxNum) {
for(int32_t i = 0; i <= arrayElements; i++) {
if (i < arrayElements/2) {
unsorted1[i] = rangeRandomAlg(minNum, maxNum);
} else {
unsorted2[i] = rangeRandomAlg(minNum, maxNum);
}
}
}
// convert the arrays to string
void arrayToString (int32_t array[], int32_t arraySize, std::string& arrayString) {
for (int32_t i = 0; i <= arraySize; ++i){
arrayString+= std::to_string(array[i]);
if (i != arraySize) {
arrayString+= ',';
}
}
}
};
/*** my functions and data for the cpp code to integrate end here ***/
class job1 : public pp::Module {
public:
job1() : pp::Module() {}
virtual ~job1() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new job1Instance(instance);
}
};
namespace pp {
Module* CreateModule() {
return new job1();
}
} // namespace pp
This is only the precompiled C++ code of the PNaCl module with my code integrated in it, it sends only the outRes1 variable = unsorted1 array variable as string to the JavaScript code in the index.html file. You have to have the .nmf and the index.html files written separately. If anyone wants to see my code of those files, which has the basic and working code for this PNaCl module should write me a comment and I’ll post those to.

Class Not Declared in Scope

Getting a "throttle not declared in this scope" error when I attempt to compile the main.cpp. I am very new to c++, so bear with me. I have the #include "throttle.h" in the headers for both cpp files, so I am not sure why when i try to create a throttle object is is not declared...
main.cpp file:
#include <stdio.h>
#include "throttle.h"
using namespace std;
int main(int argc, char **argv)
{
throttle throt1(5, 0);
throttle throt2(4, 0);
return 0;
}
throttle.h file:
#ifndef MAIN_SAVITCH_THROTTLE
#define MAIN_SAVITCH_THROTTLE
namespace main_savitch_2A
{
class throttle
{
public:
// CONSTRUCTORS
//throttle( );
//throttle(int size);
throttle(int size = 1, int start = 0); //by adding this default
//constructor the other two
//are not needed
// MODIFICATION MEMBER FUNCTIONS
void shut_off( ) { position = 0; }
void shift(int amount);
// CONSTANT MEMBER FUNCTIONS
double flow( ) const
{
return position / double(top_position);
}
bool is_on( ) const
{
return (position > 0);
}
int get_top_position()const;
int get_position()const;
friend bool operator <(const throttle& throt1, const throttle& throt2);
//postcondtion: returns true if flow of throt1 < flow of throt2.
//return false if flow of throt1 > flow of throt2
private:
int top_position;
int position;
};
}
#endif
throttle.cpp file :
#include <cassert> // Provides assert
#include "throttle.h" // Provides the throttle class definition
using namespace std; // Allows all Standard Library items to be used
namespace main_savitch_2A
{
//throttle::throttle( )
//{ // A simple on-off throttle
//top_position = 1;
//position = 0;
//}
//throttle::throttle(int size)
// Library facilities used: cassert
//{
//assert(size > 0);
//top_position = size;
//position = 0;
//}
throttle::throttle(int size, int start)
{
assert(size > 0);
assert(start = 0);
top_position = size;
position = start;
}
void throttle::shift(int amount)
{
position += amount;
if (position < 0)
position = 0;
else if (position > top_position)
position = top_position;
}
bool operator <(const throttle& throt1, const throttle& throt2)
{
return(throt1.flow() < throt2.flow());
}
int throttle::get_top_position()const
{
return top_position;
}
int throttle::get_position()const
{
return position;
}
}
In your main, it should be main_savitch_2A::throttle throt1(5, 0);.
The same for throt2.
See namespaces for further details.

How to use variables and functions declared in a header in C++

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.