So how did it evolve?
Other answers seem to be focusing on what the end point might be, but you asked how a gun could evolve, that is, what the stages of evolution could have been to result in a gun.
First, take bombardier beetles as a starting point.
They can blast noxious chemicals from their rear ends as a result of a chemical reaction between hydroquinone and hydrogen peroxide. These chemicals spontaneously combust when they come into contact, providing the force to shoot out the payload. We may suppose that your organism's ancestors had a mechanism like this, shooting a liquid mixture at a relatively low force, to burn and poison predators at close range.
From there, we can imagine that there could have been mutations that altered which particular explosive chemicals were used to propel the poison. More powerful explosive chemicals would produce greater range and higher temperature, which would be more effective at deterring predators.
A more powerful explosion would also require a stronger blast chamber, so the ancestors of your gun-creatures would have evolved stronger materials to contain the blast (thicker bone, chitin) at the same time as they evolved more explosive chemicals.
We could even imagine that if they lived in an iron-rich environment, like the scaly-foot gastropod, they could start to incorporate iron into their blast chambers, making them even stronger.
From there it's not a stretch to imagine that one of the ancestors of the gun-creatures happened to grow a bony protrusion at the front of the blast chamber. This protrusion would break off from the force of the explosion and could have helped to injure the predator at greater ranges, in addition to the poison. It would be the precursor to the bullet.
From there evolution would be a straightforward process of improving what's already there:
- More and more powerful reactive chemicals until the animal naturally produces something like gunpowder
- Stronger and stronger blast chambers to contain the explosion
- Improved shape of the blast chamber and bullet, towards something like a rifle barrel
- The ability to regenerate the bullet (as well as any damaged parts of the blast chamber) after it is fired
- Gradual loss of the vestigial poison component of the payload, in favor of an increased explosion for a faster bullet
- Eyes and brain structures to help aim the bullet more accurately at range
By the end of this process, the creatures could have something similar in range and power to a musket, though it would be single-shot and they would have to take time to regenerate the damaged blast chamber and lost bullet afterwards. What initially was a last-ditch defensive tool against predators has become something much more powerful and efficient, so that the creatures may evolve to become apex predators themselves.