Mexico  ensured itself a medal and earned a chance at Brazil by defeating Japan 3-1 in the day's opening semifinal.
Brazil, a traditional power in the sport, has never won an Olympic soccer gold medal. It captured the bronze at the 2008 Olympics with a third-place victory over Belgium.
Romulo scored first for the Brazilians in the 37th minute and they blew the game open in the second half.
Mexico fell behind early against Japan but Marco Fabian tied it in the 31st minute and Oribe Peralta scored the go-ahead goal near the midway point of the second half.
The game was not decided until Javier Cortes scored in stoppage time.
Argentina won the Olympic gold medal in men's soccer at the Beijing and Athens Games but didn't qualify for this year's tournament.