The Giants didn't disclose the terms of the deal, but the San Francisco Chronicle reported it is worth $20 million per season plus a $5 million signing bonus.
Also included is a club/vesting player option for the 2018 season.
If true, it would be the most ever paid to a right-hander.
"Matt is an integral part of the team whose performance on the mound will be one of the keys to our success for years to come," Giants General Manager Brian Sabean said.
Cain, a Cy Young Award contender, compiled a 12-11 record with a 2.88 ERA in 33 starts last season, earning him a spot on the National League All-Star team for the second time.
He tossed 7 2/3 scoreless innings in Game 2 of the 2010 World Series.
The Giants won all three games he started in the series and went on to defeat Texas in five games.
Over his seven-year career with San Francisco, Cain has racked up a 69-73 record with a 3.35 ERA.