Gold, like most other elements, was formed long ago by stars, supernovae, and other powerful cosmic events. The basis for the formation of any element from another is simple: take any two atoms and squish them together with enough force so that their nuclei actually fuse.
The first element was hydrogen, which sort of formed on its own because it is so simple. The pressure at the center of stars can compress hydrogen so forcefully that it overcomes the electrical repulsion of the nuclei and the nuclei bond due to the weak force. Depending on what atoms you are making from what, this process could either release energy or destroy it according to E=MC^2. The heavier the atom, the less energy is released, until you get to around iron, after which fusion loses energy.
Stars would fuse hydrogen into helium, then start to fuse helium, then fuse that element, until they produce iron, after which the star dies. Depending on the size of the star, there would then be a supernova, which would disperse these elements into the surrounding space. The power of a supernova, caused by the collapse and then rebound of the star due to gravity, could fuse iron into other things, and then fuse those elements. Gold, uranium, and many metals would be created this way.
All of the gold on Earth was formed this way.
Humans are able to make gold by using particle accelerators, which can speed up particles to a large fraction of the speed of light. We can then shoot a beam of atom A into a target of atom B, and some of the atoms would fuse and become gold. We are only capable of producing a very, very small amount of gold.
We have used particle accelerators in the past to create many synthetic elements that are so radioactive that they fall apart almost instantly, which is why they do not otherwise exist in the universe.