So, I read it in the US comics, which were the second iteration of the story, though not significantly different in detail, only in the narrator. Since then the story has evolved greatly, specifically with respect to the cinematic universe. The Transformers wiki explains it better than I can:
What follows is my original from-memory response, which can be considered a fair paraphrase of the wiki's text, sans newer details (such as the Fallen).
It is explained in the comics (sorry, I'm on mobile with no references handy). Unicron and Primus were godlike beings at war with each other. Primus tricked Unicron into a plantary body, along with himself in another) in order to stop him, but after many aeons they both learned how to manipulate their new corporeal forms. Unicron made himself the planet killer; Primus prepared himself for the inevitable battle by giving birth to sentient robotic beings. It was long after this, as Primus slumbered from his efforts, that the Deception faction formed and tore Cybertron (Primus ' body) into a shattered war zone.