Early in the 18th century, wives of sailors and their lovers would go with them in long journeys(sometimes prostitutes were on board too). The sailors would drink all day so when they didn’t drink they did the only other sensibly thing, with the women. When one of the women became pregnant during the trip with no land nearby. The women would be forced to give birth on the sea, they would place a clean curtain near the midship gun/cannon. The women would then give birth at that spot. Since there were many men on the ship and few women, it was hard to know who the father actually was. So they just called the baby, son of a gun, since it came out near a gun.