I am stuck with a basic understanding of the generalized (and even the ordinary version of) Gauss-Bonnet theorem. For a compact 2-dimensional Riemannian manifold $M$ with boundary $\partial M$, let $K$ be the Gaussian curvature of $M$ and $k_g$, the geodesic curvature of $\partial M$. Then

$$\int_M K\;dA+\int_{\partial M}k_g\;ds=2\pi\chi(M),$$

where $\chi(M)$ is the Euler characteristic of $M$. My questions are:

The Gaussian curvature and the geodesic curvature are functions of the connection that one puts on $M$, and in the standard version of the theorem, we usually put the induced Euclidean connection on the 2-manifold $M$ from its embedding space $\mathbb{R}^3$; whereas, the right hand side of the above equation is a topological invariant of $M$, and, thus, is independent of any connection that we adorn $M$ with. Then the left hand side, as well, should be independent of the connection. How is this invariance with respect to the connection on $M$ is concealed in the left hand side integrals?

I have only seen the statement of the generalized Gauss-Bonnet theorem (from the book "From Calculus to Cohomology") and I guess it partially answers my question, but I don't have a clear understanding of its underpinning. The generalized version says that, for any 2$n$-dimensional compact oriented smooth manifold $M$,

$$\int_M Pf\bigg(\frac{-F^{\nabla}}{2\pi}\bigg)=\chi(M)$$

holds, where $F^\nabla$ is the curvature associated with *any metric connection* on the tangent bundle of $M$. Here, $Pf:\mathfrak{so}_{2n}\to\mathbb{R}$ is something called the Pfaffian and is defined on the space of skew-symmetric matrices.

So the definition of the Pfaffian must be the answer to my question. So how does the Pfaffian make the left hand side invariant with respect to the connection? Why do we require the evenness of the dimension and orientation of $M$? And finally, why do we require a metric-compatible (perhaps, torsion free) connection in the first place?

A detailed explanation would be much appreciated. I have just started reading on Gauss-Bonnet theorem and I guess my query lies at the heart of the underlying philosophy of this gem theorem of differential topology.

Looking forward to a detailed explanation or references on this particular explanation.

(I think partial answer to my question is in Prof. Bryant's answer to this A question on Generalized Gauss-Bonnet Theorem.)

2more comments