Exit with error if user attempt to override CMAKE_INSTALL_PREFIX during installation

My project requires CMAKE_INSTALL_PREFIX to be provided during the configuration step. However, cmake allow the user to override it with cmake --install ... --prefix. That will result in a broken installation.

Is there a good way to exit with error if the prefix is different between the configuration and installation step. Perhaps there is a way to write install(CODE ...) to compare cached value against the current value?

install(CODE) sounds like the way to do it to me. install(SCRIPT) with a configure_file()'d script may be more convenient.

Could you provide an example about how to use install(CODE) to get this behavior?

The pre-configure_file code you want there is something like:

if (NOT CMAKE_INSTALL_PREFIX STREQUAL "@CMAKE_INSTALL_PREFIX@")
    message(FATAL_ERROR …)
endif ()

The in-script code should have a literal on the RHS of that comparison.