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