Some main-sequence stars of spectral type A are observed to have a strong (0.03-3 tesla), static, large-scale magnetic field, of a chiefly dipolar shape: they are known as 'Ap stars', such as Alioth, the fifth star in the Big Dipper. Following the discovery of these fields, it was proposed that they are remnants of the star's formation, a 'fossil' field. An alternative suggestion is that they could be generated by a dynamo process in the star's convective core. The dynamo hypothesis, however, has difficulty explaining high field strengths and the observed lack of a correlation with rotation. The weakness of the fossil-field theory has been the absence of field configurations stable enough to survive in a star over its lifetime. Here we report numerical simulations that show that stable magnetic field configurations, with properties agreeing with those observed, can develop through evolution from arbitrary, unstable initial fields. The results are applicable equally to Ap stars, magnetic white dwarfs and some highly magnetized neutron stars known as magnetars. This establishes fossil fields as the natural, unifying explanation for the magnetism of all these stars.