The magnetic anisotropy energy (MAE) of hcp Gd was calculated from first principles using the full-potential linear muffin-tin orbital method. It was found that the principal contributions to the MAE are the dipole-dipole interaction between the localized 4f spins and the spin-orbit interaction of the valence band states. The dipole contribution has the form 1/2K(1)(d)(1-cos 2 theta), where theta is the angle between the magnetization direction and the c axis. The contribution of the spin-orbit interaction is shown to arise from the polarization of the conduction band that becomes exchange split due to exchange interaction with the localized 4f electrons. We argue that this leads to significant contributions from higher order anisotropy constants. An imposed reduced 4f moment leads to a repopulation of the electronic states at the Fermi level and a reduced exchange splitting of the valence states, which we demonstrate leads to a modification of the MAE. This modification is in qualitative agreement with the observed temperature dependence of the MAE. In addition, the dependence of the MAE on the c/a ratio has been studied.