I had promised here to do a quick explanation on how to access global variables from several c++ source files.
The general idea is that global variables must be defined once only for the entire program. Any file that needs to access the same variable is told of it’s existence but does not declare it.
In main.cpp I declare two globals, instances of the motor class, LeftMotor and RightMotor.
main.cpp
#include "vex.h"
using namespace vex;
// A global instance of vex::brain used for printing to the V5 brain screen
vex::brain Brain;
// define you global instances of motors and other devices here
vex::motor LeftMotor( vex:: PORT1 );
vex::motor RightMotor( vex:: PORT10, true );
int main() {
int count = 0;
driveForwards( 100 );
this_thread::sleep_for(1000);
driveForwards( 0 );
while(1) {
Brain.Screen.printAt( 10, 50, "Hello V5 %d", count++ );
// Allow other tasks to run
this_thread::sleep_for(10);
}
}
(main also want to call the function driveForwards
we deal with that in a similar way to the globals as the function itself is essentially global)
In a second source file, drive.cpp, we have a single function called driveForwards that wants to use the LeftMotor and RightMotor variables.
drive.cpp
#include "vex.h"
using namespace vex;
void
driveForwards( int32_t speed ) {
LeftMotor.spin(fwd, speed, velocityUnits::rpm );
RightMotor.spin(fwd, speed, velocityUnits::rpm );
}
now to hook it all together, in vex.h declare both LeftMotor and RightMotor as extern. The driveForwards function is also declared (a function prototype).
vex.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "v5.h"
#include "v5_vcs.h"
extern vex::motor LeftMotor;
extern vex::motor RightMotor;
void driveForwards( int32_t speed );