How does the Sonic & Knuckles cart detect another cartridge?
It checks the serial numbers of games; they can be found in the ROM’s header. It probably detects all preceding Sonic the Hedgehog games since they all result in specific effects when locked-on.
Are the game ROMs merged in some way when connected?
It seems both games are simply mapped onto memory. This way, the executing game code gets access to the contents of both games.
To better understand what this means, imagine a Sonic & Knuckles ROM with the complete contents of the Sonic the Hedgehog 3 ROM concatenated onto it.
The address space represents memory the game code can access. The contents of the read-only memory chips get mapped onto the Mega Drive’s 68k processor’s 24-bit address space. The Mega Drive just sees two games, one after another. Incidentally, that’s what a good dump of Sonic 3 & Knuckles looks like. This explains why the game works even in emulators that don’t support any of the custom hardware inside the Sonic & Knuckles cartridge.
Any game locked onto Sonic & Knuckles will probably have its ROM mapped onto the game’s address space the same way. This means game’s data is made available for use by the Sonic & Knuckles game code; it does not necessarily mean the data will be used. Since Sonic & Knuckles was programmed to work with Sonic the Hedgehog 3, it makes extensive use of the data in the locked-on cartridge. Its handling of other games is far less sophisticated; apparently, it just uses the metadata found in the ROM’s header to generate a unique Blue Spheres stage. If it detects that it’s the first Sonic the Hedgehog game, it simply unlocks the full version of the bonus game.
The connection to Sonic the Hedgehog 2 works similarly:
There are two ROM chips in the Sonic & Knuckles cartridge: one has the main game and the other has a patch for Sonic the Hedgehog 2. The patch ROM contains the complete Knuckles the Echidna in Sonic the Hedgehog 2 game code; this is the full code for the original game but modified with the necessary game mechanics for Knuckles: lower speed, lower jump height, flight, wall climbing, etc. The ROM also contains new graphics data for Knuckles as well as new map data with places and items for Knuckles to reach with his abilities.
When Sonic & Knuckles detects that Sonic the Hedgehog 2 is locked on, it passes control of the process