error: 'set' was not declared in this scope - c++

I've already searched through this site and on Google, but I couldn't find anything helping me. I'm a total C++ noob and started coding yesterday, today I've spent couple of hours trying to figure out what I did wrong and I was already able to resolve like 10 errors (which is a lot in such a small code section, I know ._.). What did I do wrong? I do have small Java knowledge and a few scripting languages like LUA and Autoit3.
This is just a small program to test the GPIO pins on my Raspberry PI and to get used to the C++ syntax and to learn a little about programming.
Edit: The error occurrs twice, I've noted that down using comments
#include <wiringPi.h>
#include <stdio.h>
#include <iostream>
using namespace std;
//Declaration of global variables
int delayTime;
//Gets executed once to setup parameters
static int setup() {
delayTime = 750;
}
//Gets executed until ESC is pressed
static int program() {
set(0, 1); //FIRST ERROR
set(5, 0);
delay(delayTime);
set(0, 0);
set(5, 1);
delay(delayTime);
}
//Main function getting called at program start
int main() {
bool running = true;
setup();
puts("Press 'STRG+C' to exit the program. Then run './off'");
if (wiringPiSetup() == -1)
return 1;
pinMode(0, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
set(4, 1); //SECOND ERROR
while (running) {
program(); //Run the code above
}
digitalWriteByte(0);
return 0;
}
//Shortcuts for basic functions
static int set(int pin, int state) {
digitalWrite(pin, state);
return 0;
}
static int get(int pin) {
return digitalRead(pin);
}

You are calling set() before it has been declared. Either move the function up in the file, so that it is above the first place it is called, or add a forward declaration like this:
static int set(int pin, int state);

C/C++ compilers are dumb — they proceed top-down. At the time that you call set() from main(), the compiler still doesn't know what set() is yet, because it hasn't seen the definition.
One solution is to write an explicit declaration of set() before main() is defined. An easier approach would be to move main() to the end, as is conventional — precisely because of this issue.

C++ compilation is dependent on order. If you call something that was not yet declared, you get an error. Either move your functions body to a place before it's called, or place a forward declaration there.

Related

I cannot get an MBED ticker within a class to call a member method

I wrote the following MBED-based C++ program as an experiment for a more detailed project I am working on for my Nucleoboard Microcontroller:
#include "mbed.h"
DigitalOut greenLed(PA_5);
#include "mbed.h"
class TimedLED
{
public:
TimedLED()
{
Ticker t;
t.attach_us(this, &TimedLED::flip, 1000000);
}
void flip(void)
{
static int count = 0;
greenLed.write(count%2); //-- toggle greenLed
count++;
}
};
int main()
{
TimedLED flash;
while (1);
}
All the references I looked at seemed to indicate that t.attach_us(this, &TimedLED::flip, 1000000) should call the method, 'flip' every second and so cause the LED to toggle on and off. This is not happening, however. I cannot see what the problem is. I hope someone can help me clear this up.
I am getting the following warning message indicating that this format is deprecated, but the link to the documentation was broken, so I couldn't get more details:
Function "mbed::Ticker::attach_us(T *, M, us_timestamp_t) [with T=TimedLED, M=void(TimedLED::*)()]" (declared at /extras/mbed_fd96258d940d/drivers/Ticker.h:122) was declared "deprecated" "t.attach_us(this, &TimedLED::flip, 1000000);"
Even if it is deprecated, it still should work, shouldn't it? Also, presumably if the deprecation message is correct, there is a newer way to do the same thing. I can't find reference to an alternative method though anywhere.
You declare Ticker t; in your constructor on the stack, when the constructor exits it will clear the object, and thus the code will not run.
Declare the variable in your class, and it'll run as expected:
class TimedLED
{
public:
TimedLED()
{
t.attach(callback(this, &TimedLED::flip), 1.0f);
}
void flip(void)
{
static int count = 0;
greenLed.write(count%2); //-- toggle greenLed
count++;
}
private:
Ticker t;
};
Also note the change in the constructor, this is the prefered (non-deprecated) way to attach callbacks in mbed OS 5.

May EXC_BAD_ACCESS be related to function length?

I have created a class in a Finite Element Method code in C++. I am using AppleClang 8.0.0.8000042.
One method in my class is fairly large, over 45k lines (after indenting it. Before, i.e., line breaks only after ; and }, it was around 1.5k). I know this is bad practice, but for now I don't really see other option for what I am doing in this method.
The first instruction in this method calls another method for the same class. When I run it in serial mode (The framework I am developing in has multi-threading support) I have no problems. However, if I use the multi-thread mode(on the same computer), even with only 1 thread, I get a EXC_BAD_ACCESS (code = 1, address=0x6ffffffa3280).
Ok, I thought I had messed up somewhere else. When I ran out of options I decided to just erase most of my colossal method, turning it into a useless but short method with just that instruction that would cause me the EXC_BAD_ACCESS error. However, it did solve the problem.
The situation is something like this:
Bad scenario
//A.cpp
int A::foo() const{ return 2;}
void A::fun(const double & in_param){
double out;
this->func(in_param, out);
...
}
void A::func(const double& in_param, double &out_param){
const int fooVar = this->foo();//EXC_BAD_ACCESS
...
(45k lines of code)
...
}
Good scenario
//A.cpp
int A::foo() const{ return 2;}
void A::fun(const double & in_param){
double out;
this->func(in_param, out);
...
}
void A::func(const double& in_param, double &out_param){
const int fooVar = this->foo();//fooVar = 2
}
Would anyone know why does this happen? And why does it happen only when multithreading?
I swear I will try to think on a way to reduce the length of the method, but I am quite curious on why I got that error.

Arduino variable usage

I'm a newbie when it comes to Arduino and C++.
I'm trying to write a program that reads the input data from analog pin zero (a POT).
after the value is read I want it to print to the serial monitor, but only once. if the value of from analog pin zero changes I want it to print the new value to the serial monitor. I'm trying to use global variables, but to no avail. any help would be greatly appreciated!
int entered=0;
int flag;
void setup()
{
Serial.begin(9600);
}
void loop() {
int potValue=analogRead(A0);
if (!entered){
entered=1;
Serial.println(potValue);
}
int flag=potValue;
if (flag!=flag){
entered=0;
}
}
That is really close. This line is your mistake
int flag=potValue;
As written, that creates a new local variable flag. The local variable hides the global variable. So the comparison is always to itself and never fails. Change the line to :
flag=potValue;
and your program will function as desired.
You can save some memory and code space like this:
int g_lastValue = 0;
void loop() {
int nowValue = analogRead(A0);
if (nowValue != g_lastValue) {
Serial.println(nowValue);
g_lastValue = nowValue;
}
...
}
The use of g_ as name prefix is a cue that a variable is global. I use this naming convention as it helps when reading a function to know variables that are not local. Without a name cue, you need to scan the entire function body to see if there is a variable declaration present, and only by looking through the function and not finding a declaration can you know the variable must be global. On small functions, not really an issue, but as your code grows, you may want some self documentation a naming convention provides.
You're on your way but you are getting tangled a bit in variables.
It can be simpler: just one global variable and one conditional check.
int lastRead = -1; // init to value outside of possible range
void setup()
{
Serial.begin(9600);
}
void loop() {
// get current value
int currentRead = analogRead(0);
//compare and only print if !=
if (currentRead != lastRead){
lastRead = currentRead; // store
Serial.println(lastRead);
}
}

if statement in main function c++

Okay, probably a dumb question to you guys but I can't figure it out.
So I'm taking a c++ basics course in class and so far I'm struggling/crying.
I can't show you guys my code because I'm not allowed/there are consequences if I'm caught but I could probably give a example.
I'm using xcode. So when I compile, I get two errors below (image provided).
I searched for similar questions, but those seem too complex compared to what I'm doing. In addition, the only includes I have are iostream and string.
I know the problem occurs when I add an if statement in my main function. I know this because when I delete it, everything compiles as expected. Yet when I add it again to the main function, these errors occur.
So my question is, based on what I know, is it proper to add an if statements whenever in the main function?
Below is an example. I wrote the functions below and called above.
#include <iostream>
#include <string>
using namespace std;
// example functions that I just made up to explain the structure of my actual code.
//Don't bother trying to understand it. It's just to explain that
//I wrote my functions at the
// bottom and called it at the top.
int getNumberofWins(param1, param2);
string getTheName(int player1);
int executeCycle(string p1_name, string p2_name);
void stateWinner(string winner_name);
int main {
playerOne = getTheName(1);
playerTwo = getTheName(2);
r1 = executeCycle(playerOne, playerTwo);
r2= executeCycle(playerOne, playerTwo);
totalWin1 = getNumberOfWins(1, r1, r2);
totalWin2 = getNumberOfWins(2, r1, r2);
cout << totalWin1;
//This is the where I get the errors. When I delete the if statement,
//Everything compiles. When I add it, an error occurs.
if (totalWin1 == 2){
stateWinner(playerOne);
}
return 0;
}
string getTheName(int player1){
string playerOne;
string playerTwo;
if(player_number == 1){ code code code
}
}
int getNumberofWins (int param1, int param2){
code code code
}
int executeCycle(string p1_name, string p2_name){
code code code
}
void stateWinner(string winner_name){
if(!winner_name.empty()){
code code code
}
I hope it's fine if the code above isn't accurate. I think the point is that once I add my if statement to the main function, the two errors show up.
actually...now that I look at it, they both seem like similar errors. I just don't know why they both appear...
Sorry if this is an obvious answer or if it isn't clear.
The "announceWinner" function is not defined anywhere, ie there's no
void announceWinner () {
// code
}
anywhere. Either you haven't written it yet, or the file that contains it is not being compiled & linked with the main program.

Visual Studio Compiler is highlighting Static variables differently?

I'm programming in C++ and have a method which uses a static variable. The method isn't working as I think it should; upon investigation, I found that my static variable is being highlighted in red in two places and blue in other places. Below is the code:
int GameModeState::changeJob(int number)
{
static int job = 1; //red
if (number == 1)
{
job = (job+1); //First one is red, second one is blue
return job; //blue
} else {
return job; //blue
}
}
I'm calling this method with other methods, one shown for example:
int GameModeState::getJob()
{
int currentJob = (changeJob(2));
return currentJob;
}
I want a method like getJob() to simply return the current value of job, while another method, when calling changeJob(number) is changeJob(1), to increment job's value by one. (Hence the if/else statement in changeJob(number)).
Since the job variables are highlighted differently, I'm thinking the compiler is saying that it views the two separately somehow? I'm getting stuck with job being some even value.
EDIT I also have Awesomium... I believe that is the only addition to the compiler, but I'm not completely sure.
MOAR EDIT In another class, I have a method which should determine the current job's number and do something based on if the number is even or odd (since right now there are only two jobs)
void ZoneMovementState::_changeZone(const String& message, const Awesomium::JSValue& input, Awesomium::JSValue& output)
{
//Awesomium::JSValue::Object object = input.getObject();
//String zoneFilename = Convert::toString(object[L"zoneFilename"].toString());
// If the number from getJob is even, the player is currently a geologist
if (GameModeState::getJob()%2 == 0)
{
ZoneParser::getSingleton().load("../media/zones/geology_zone.xml", false);
} else {
ZoneParser::getSingleton().load("../media/zones/farm_zone.xml", false);
}
transitionHandler->go();
}
Ignore the two commented out lines; they deal with JS, which I'm not working on for now.
In the program, I can access the farm_zone until I increment job's value using the below method in GameModeState:
void GameModeState::_openNotebook(const String& message, const Awesomium::JSValue& input, Awesomium::JSValue& output)
{
mNotebookTransition->go();
static int currentJob = changeJob(1);
}
.... So I figured out my problem. While going through the code to show you guys, I realized that the static for currentJob was probably unneeded... once I removed it, my code works as it should now.
Thanks for the help guys!
Part of the problem here is you're using a static local for what very likely should just be a member variable. A static local maintains it's value across all calls to a function in all threads in a process. It's much more likely that you want it to persist for all calls to changeJob in a particular GameModeState instance (else why make it a member functon to begin with?).
To do this you'll need to define a member variable on GameModeState initialize it in the constructor and then access it in the method. For example
class GameModeState {
int job;
GameModeState() : job(1) {}
int changeJob(int number);
};
int GameModeState::changeJob(int number) {
if (number == 1) {
job = (job+1);
return job;
} else {
return job;
}
}
Note: I'm not entirely sure why you're seeing the color's your are seeing. Visual Studio by default won't color member variables a particular color in C++ so it's very likely another add-in you are using.
Nah, highlighting doesn't mean anything. That is, the editor doesn't call the compiler before deciding how/what/when to highlight. So that is not your problem. Sorry 'bout that :-)
You can prove this to yourself by going to Tools->Options->TextEditor and noticing that you can change the highlighting by choosing a different text-editing model.