SIGSEV when declaring ofSoundPlayer at file scope on Android

This is total beginner question, but when I declare a variable of type ofSoundPlayer at file scope on osx it works fine but on android it causes some sort of crash loop in libc. I can get around this by declaring the ofSoundPlayer as part of the ofApp class instead of at file scope, but I am curious as to why this happens.

declaring static variables like that is really problematic. if the variable constructor tries to do any call to anything that is initialized in main it will fail or crash the application. also destruction of the object can be problematic. in this case it might be because the object is trying to access some java class that is not created yet but not sure. in any case it’s not a very good practice to create an object like that

Ok, I’ll avoid it in the future. Does the same warning apply to something like this function?

void ofApp::playSound(std::string fileName, int volume) {

	static ofSoundPlayer foregroundSound;

    foregroundSound.loadSound(fileName, true);
    foregroundSound.setVolume(volume);
    foregroundSound.play();
}

that’s slightly better cause it won’t be initialized until the first call to that function but you still have no idea when it’s going to get destroyed. in general avoid static variables for complex objects, it’s better to have it as an instance variable where the time it’s initialized and destroyed is perfectly controlled

1 Like