Asteroids with satellites are observed throughout the Solar System, from subkilometre near-Earth asteroid pairs to systems of large and distant bodies in the Kuiper belt. The smallest and closest systems are found among the near-Earth and small inner main-belt asteroids, which typically have rapidly rotating primaries and close secondaries on circular orbits. About 15 per cent of near-Earth and main-belt asteroids with diameters under 10km have satellites. The mechanism that forms such similar binaries in these two dynamically different populations was hitherto unclear. Here we show that these binaries are created by the slow spinup of a `rubble pile' asteroid by means of the thermal YORP (Yarkovsky-O'Keefe-Radzievskii-Paddack) effect. We find that mass shed from the equator of a critically spinning body accretes into a satellite if the material is collisionally dissipative and the primary maintains a low equatorial elongation. The satellite forms mostly from material originating near the primary's surface and enters into a close, low-eccentricity orbit. The properties of binaries produced by our model match those currently observed in the small near-Earth and main-belt asteroid populations, including 1999KW4 (refs 3, 4).