I was writing a small program in C that utilizes SDL 2.0, and ran into a problem when I couldn't get SDL_NumJoysticks()
to report the number of joysticks plugged in at the time of the function call. I believe that it is reporting the number of joysticks connected during one of SDL's initialization functions (I would guess 'SDL_Init()', but I have no evidence), and then keeps on giving you that number throughout the rest of the program. Here is a short test program that I have been using:
#include <stdio.h>
#include <SDL2/SDL.h>
int main() {
SDL_Event event;
SDL_Window *window;
short joysticks = 0;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError());
return 1;
}
window = SDL_CreateWindow("Test window", 0, 0, 800, 600, SDL_WINDOW_SHOWN);
if (window == NULL) {
fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError());
return 1;
}
printf("%s\n", SDL_GetError());
while (1) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
printf("%s\n", SDL_GetError());
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
} else if (event.type == SDL_JOYDEVICEADDED) {
printf("Joystick added!\n");
} else if (event.type == SDL_JOYDEVICEREMOVED) {
printf("Joystick removed!\n");
}
}
if (SDL_NumJoysticks() > joysticks) {
printf("Joystick inserted.\n");
joysticks++;
} else if (SDL_NumJoysticks() < joysticks && SDL_NumJoysticks() >= 0) {
printf("Joystick removed.\n");
joysticks--;
} else if (SDL_NumJoysticks() < 0) {
printf("Something went wrong!\n");
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}
}
return 0;
}
The program accurately reports the number of joysticks plugged in when the program is started, but does absolutely nothing after that.
The official SDL docs for SDL_Numjoysticks() state that it "Returns the number of attached joysticks on success". How can I get it to tell me the number of joysticks plugged in at the time of the function call? Am I making a mistake in my code, or is that just not the way that SDL_NumJoysticks()
works?
Make sure you follow these steps and see if you still have problems:
EDIT: More info that I think should be useful: