CBS Corp. and Viacom Inc. agreed to merge, a deal the media companies hope will put them on stronger footing to compete with larger rivals in a business buffeted by cable TV cord-cutting and increasingly dominated by streaming.

The all-stock deal, if completed, will reunite the media empire of mogul Sumner Redstone, who had split up CBS...