The team said the deal includes club options for 2022 and 2023.
The deal is worth $51 million, which sets a new standard for a player in his first year of arbitration eligibility.
The previous record for a first-time arbitration-eligible pitcher was established by Cleveland's Corey Kluber when he signed a five-year, $38.5 million deal in April 2015.
"This type of contract is all about the future,'' general manager John Mozeliak said Thursday. "This is about future earnings, and when you have someone at 25 years old who can hit free agency at 28, his leverage is far different than someone hitting free agency at 32 and not having to earn much at that point. Carlos felt it was important to get something done now."
Martinez, speaking through a translator, called the contract "something I've always dreamed of for myself, for my family, since I was a little boy growing up in the Dominican Republic.
"Thinking of my future, my age, I really thought this was an opportunity I couldn't let go of,'' he said Thursday. "The Cardinals were offering it to me and I said, 'Why not?'"
The Cardinals have made a habit of locking up their best young talent to multiyear deals early in their careers in order to buy out arbitration and free-agency years. They cut similar agreements in recent springs with Kolten Wong and Matt Carpenter.
Manager Mike Matheny was with Martinez last week in the Dominican Republic for a charity event, and he said the pitcher's excitement was building toward an agreement.
"The first time a guy gets a big contract is a huge deal," Matheny told ESPN on Thursday. "It was just a matter of seeing if it worked for both sides and I believe everyone is very happy where this stands. It's just been so impressive how much he has grown up the last couple years."
Martinez, 25, had a 3.04 ERA in 31 starts for the Cardinals last season, emerging as the team's No. 1 starter during an off season for longtime ace Adam Wainwright. An All-Star in 2015, Martinez has a 3.32 ERA in four major league seasons.
"He could be the No. 1 pitcher in the league," Matheny said. "I think he has Cy Young ability."
"I love it here," Martinez told ESPN.com last season while standing in the Busch Stadium home dugout. "I want to stay here all my life."
Until Wednesday, the Cardinals had indicated publicly that they were heading to an arbitration hearing with both Martinez and Michael Wacha, who remains their only unsigned arbitration-eligible player. Martinez's hearing was scheduled for Feb. 8.