clinuxfunctionscoping

Using a variable defined in another function


I'm trying to control a joystick, written some code using the API to do so. I've read the number of axes on the joystick in function a using ioctl(fd, JSIOCGAXES, &axes); and want to then print the axis that was moved in the event-handling function (function b):

char whichaxis[axes] = {'X','Y','Y','X'};
printf("%c%c |%8hd\n",whichjs,whichaxis[jse.number],jse.value);

This code should print something like LX| -32768, saying that the left joystick has moved in the x direction.

However, this returns an error, as I am calling axes in function b but it is not defined in function b. So my question is, how can I use axes despite it not being defined in function b?

Here is the code

// Returns info about the joystick device
void print_device_info(int fd) {
    int axes=0, buttons=0;
    char name[128];
    ioctl(fd, JSIOCGAXES, &axes);
    ioctl(fd, JSIOCGBUTTONS, &buttons);
    ioctl(fd, JSIOCGNAME(sizeof(name)), &name);
    printf("%s\n  %d Axes %d Buttons\n", name, axes, buttons);
}

// Event handler
void process_event(struct js_event jse) {
     // Define which axis is which
     //        Axis number {0,1,2,3} */
     char whichaxis[axes] = {'X','Y','Y','X'};
     //Define which joystick is moved
     char whichjs = '*';
     switch(jse.number) {
         case 0: case 1:
             whichjs = 'L';
             break;
         case 2: case 3:
             whichjs = 'R';
             break;
         default:
             whichjs = '*';
             break;
     }
     // Print which joystick, axis and value of the joystick position
     printf("%c%c |%8hd\n",whichjs,whichaxis[jse.number],jse.value);
}

Solution

  • axes is a local variable that is declared inside a function. A local variable can only be used in the function where it is declared. A global variable is a variable that is declared outside all functions. So make axes a global variable which can be used in all functions.

    int axes; // Global declaration makes axes which as scope in all below functions
    
    void print_device_info(int fd) {
        ...
        ioctl(fd, JSIOCGAXES, &axes);
        ...
    
    void process_event(struct js_event jse) {
        char whichaxis[axes] = {'X','Y','Y','X'};
        ...