Stars are known to form in clouds of cold molecular hydrogen, which are relatively poorly understood despite being one of the main components of the interstellar medium. The problem is that H2 is invisible in the cold interstellar medium, so its distribution and motion must be inferred from observations of minor constituents of the clouds, such as carbon monoxide and dust. Most of our present knowledge comes from observations of CO emission, but there is much debate on whether this is an effective tracer of H2: it might miss a large fraction of the molecular gas. It is difficult to address this question on the basis of observations within the Milky Way alone, whose edge-on orientation makes it hard to discern the distant cloud structures. We have therefore surveyed the CO emission of the molecular clouds of M31 (the Andromeda galaxy), the nearest spiral galaxy to the Milky Way, and investigated the extent to which it follows the extinction of starlight by dust. We find a remarkably tight association between the CO emission and the dust, from which we conclude that CO does indeed trace all of the molecular gas.