All of the atoms of gold in the universe were forged in the collapse of dying stars in a process called nucleosynthesis. For heavy elements, such as gold, this process occurs mainly during the last stages of the star's life as it undergoes final collapse and supernova.
Gold is a heavy element that was not present in the early universe. The process of synthesizing gold began with the formation of the first stars. Main-sequence stars produce energy by fusing hydrogen into heavier elements throughout their lifespan. This process stops at iron and nickel, however, as the fusion of these nuclei takes more energy than it produces and cannot be sustained. Elements heavier than iron, such as gold, can only be produced during the final collapse of supermassive stars. This process, called a core-collapse supernova, occurs when a star, which might be hundreds of times the mass of the Sun, can no longer support itself against its own gravity. The outer layers of the star fall in toward the core, drastically increasing the pressure and temperature, until atomic nuclei begin to fuse again. This rapid fusion transmutes elements present in the star and generates all of the heaviest elements of the periodic table. Gold, and the other elements thus created, are scattered by the explosion and drift through space to be taken up by new solar systems and eventually by worlds such as Earth.