Origins of the theory
Comparative advantage was first described by Robert Torrens in 1815 in an essay on the Corn Laws. He concluded it was England's advantage to trade with Poland in return for grain, even though it might be possible to produce that grain more cheaply in England than Poland.
However it is usually attributed to David Ricardo who explained it clearly in his 1817 book On the Principles of Political Economy and Taxation in an example involving England and Portugal. In Portugal it is possible to produce both wine and cloth with less work than it takes in England. However the relative costs of producing those two goods are different in the two countries. In England it is very hard to produce wine, and only moderately difficult to produce cloth. In Portugal both are easy to produce. Therefore while it is cheaper to produce cloth in Portugal than England, it is cheaper still for Portugal to produce excess wine, and trade that for English cloth. And conversely England benefits from this trade because its cost for producing cloth has not changed but it can now get wine at closer to the cost of cloth.
The conclusion drawn from this is that a country should specialize in products and services in which they have a comparative advantage. They should then trade with another country that has products in which that country has a comparative advantage. In this way both countries become better off.