Proper coastal defence guns (as opposed to simple anti-invasion weapons placed to fire on invading forces) have many advantages over ships: firstly a coastal defence gun, properly emplaced, is very difficult for a ship to even spot, let alone hit. A ship off the coast is somewhat obvious.
A ship can be disabled or sunk by hits that do not hit the ship's own weaponry. For a ship to destroy a coastal defence weapon a direct hit is required. Direct hits are hard to get when firing from a moving ship on a small target.
Usually coastal defence weapons form part of a larger system, with separate and hidden spotting and ranging installations, which were also in communication with each other, giving not only better spotting ability but also as these were usually some distance apart they provided much better triangulation for ranging purposes, and could each contribute to spotting shell spouts.
Edited by DougRichards, 13 June 2019 - 0730 AM.