ATHENS — Macedonia signed a landmark agreement on Sunday to change its name to North Macedonia, sealing a deal with Greece that would, if ratified, resolve a decades-old dispute and pave the way for the enlargement of the European Union and NATO.

Hailing a “patriotic and mutually beneficial agreement for both peoples,” Prime Minister Alexis Tsipras of Greece said it was important to see the accord through.

The accord must still pass a referendum in Macedonia and ratification in the parliaments of both countries.

“It is our historic responsibility to ensure that this step we are making is not left up in the air,” he said.

The Greek and Macedonian foreign ministers signed the agreement on the banks of the Prespa Lake District in northern Greece, which the two countries share along with Albania, in a ceremony attended by Mr. Tsipras and Prime Minister Zoran Zaev of Macedonia.

The ceremony formalized an agreement that the countries announced on Tuesday.

“We have put an end to the longstanding problems which aggravated our bilateral ties,” Mr. Zaev said. “Our two countries must leave behind the past and look to the future,” he said. “Good luck to us.”

For decades, Greece has objected to the former Yugoslav republic’s use of the name Macedonia, arguing that it implies territorial aspirations against a northern Greek region with the same name. Athens also claimed that using the name was an attempt to appropriate the ancient civilization of Macedonia, a Greek kingdom ruled by Philip II and Alexander the Great.

Successive Greek governments have used the country’s veto to keep Macedonia out of the European Union and NATO until a resolution of the name dispute. Now, assuming the deal is formally ratified, Mr. Tsipras has pledged that Greece will lift its objections to Macedonia joining those alliances.

Among the foreign dignitaries attending the tightly guarded ceremony were the European Union’s top foreign policy official, Federica Mogherini; and Matthew Nimetz, the United Nations special envoy, who has mediated the dispute for a quarter- century......