Reapply the commit 43b508566799751aa180f1eaaafc5be693f2f1ae with additional fixes for building with BUILD_SHARED_LIBS=ON.