Is it possible to declare a sylib motor as a global variable?

When declaring a sylib motor as a global variable, it causes a memory error. Based on my testing, this is because the motor needs to be declared after sylib::initialize(). However, declaring it after sylib::initialize by putting it in main prevents me from using it in files or even other functions in the same cpp file. Is there any way to declare a sylib motor as a global variable without causing a memory error?

I’m not seeing a memory error, do you have an example that demonstrates it ?

3 Likes

Hey, sorry for the late reply. I get a memory error when my code looks like this:

#include "vex.h"
#include "sylib/sylib.hpp"

auto motor = sylib::Motor(17,200, true, motor_speed_controller);

int main() {

  sylib::initialize();

  // Prevent main from exiting with an infinite loop.
  while (true) {
    wait(100, msec);
  }

Meanwhile, I don’t get an error when I do this:

#include "vex.h"
#include "sylib/sylib.hpp"


int main() {

  sylib::initialize();

  auto motor = sylib::Motor(17,200, true, motor_speed_controller);

  // Prevent main from exiting with an infinite loop.
  while (true) {
    wait(100, msec);
  }

I appreciate any and all help you can give me, and sorry in advance if I’ve missed something really obvious. Thank you!

When you create a motor in the global scope, it’s being created before sylib::initialize is called, as variables in the global scope are initialized before the main function runs. Here is how you should actually do it:

#include "vex.h"
#include "sylib/sylib.hpp"

sylib::Motor motor;

int main() {
  sylib::initialize();

  motor = sylib::Motor(17,200, true, motor_speed_controller);

  // Prevent main from exiting with an infinite loop.
  while (true) {
    wait(100, msec);
  }
6 Likes

Alright, I’ll give this a shot when I can next get access to a brain on Saturday. Thanks for the response.

yea, that’s probably not going to work, I don’t think sylib has a default constructor for the Motor class. The root cause of the memory error is use of vex::mutex in the constructor (and in sylib::initialize() IIRC if that was called as part of a new class in the constructor) outside of a running task. vexos 1.1.3* actually stops the crash (I made a change to handle this issue back in February) but I have no idea if the code then actually works. You have the source for sylib and with suitable changes it could be made to work, I guess that’s the point of using an open source library, understand how it works and change as necessary for your requirements.

*vexos 1.1.3 is not released yet.

6 Likes

Yes, this has been somewhat of a pain for me to deal with. I haven’t found a solution that works in all cases on all platforms. I’m hopeful that with 1.1.3 I can make it work better.

4 Likes