Closing multiple windows when any are closed

I have a Windows application based on multiWindowOneAppExample.
I would like to close both windows when either are closed by the user.
I tried defining an exit method for the GUI

void ofApp::exitGui(ofEventArgs & args) {
	exit();
}

and then adding it as a listener

	ofAddListener(guiWindow->events().exit, mainApp.get(), &ofApp::exitGui);

But it doesn’t get called when the main window is closed.

I also tried closing the gui window explicitly in ofApp::exit() but then I get an access violation in ofAppGLFWWindow::getWindowShouldClose() after the window has closed.

So, is there a correct way of achieving this?

Thanks,
Richard

Well I found a way of doing it.

After adding the listener as above ofApp::exit() gets called when either window is closed.
Then this code closes both windows

void ofApp::exit() {
	if (!exiting) {
		exiting = true;
		ofExit();
	}
}

The exiting flag is required to prevent a crash as ofApp::exit() now gets called twice.

I still don’t understand why

ofAddListener(guiWindow->events().exit, mainApp.get(), &ofApp::exitGui);

causes ofApp::exit() to be called instead of ofApp::exitGui()