Hammers became common upon the invention of the percussion cap. Prior to its invention, most guns were ignited using flint (the portion of a flintlock which holds the flint was called the cock). Other designs, such as the wheellock and matchlock, didn't use impact to fire the gun, so no hammer was needed.
Early hammers looked a lot like their namesakes, and they perform the same function as any hammer: to clobber something in order to produce an intended effect.
The first hammers struck percussion caps directly. In cartridge guns, some hammers strike the cartridge directly, while others strike a firing pin, transfer bar, or some other portion of the gun in order to fire it.
Not all guns contain hammers, and some hammers in firearms are not readily recognized as such, due to their sometimes-unusual shapes. Some hammers are exposed and may be cocked by hand, and others are contained inside the gun and are not visible without disassembling the gun.
Early guns (especially shotguns) containing internal hammers were often advertised as "hammerless," and though that term is a misnomer because the guns do actually contain hammers, it is still used.