At a joint news conference with Mr Ghani in the Afghan capital, Mr Cameron said Britain would always be a “strong partner and a good friend” to Afghanistan.
He reiterated that the UK is committed to fighting Islamic militants across the Middle East – including those from IS, who have taken control of large swathes of Syria and Iraq.
He said: “This is where al Qaeda trained their terrorists, this is where 9/11 and countless other plots were hatched.
“An Afghanistan free from al Qaeda is in our national interests as well as Afghanistan’s, and now, 13 long years later, Afghanistan can and must deliver its own security.
“The work of defeating Islamist extremist terror goes on elsewhere and because this threatens us at home, we must continue to play our part.”
Earlier, Mr Cameron announced two more RAF Tornado bombers will be joining the mission against IS in Iraq.
The trip comes days after Afghanistan’s new president signed vital security agreements allowing foreign troops to remain in the country beyond the end of this year.
The Status of Forces Agreement was long overdue. It provides the legal framework for international forces to train and mentor Afghan counterparts.
David Cameron will hold bilateral meetings with both President Ghani and his opponent in the elections, Abdullah Abdullah, who has been appointed Chief Executive in an power-sharing agreement that is hoped will bring peace to Afghanistan.
The Taliban has described it as a “US orchestrated sham”.
President Ghani came to power at a risky moment for Afghanistan as foreign combat troops prepare to pull out at the end of the year.
Afghan forces will be responsible for their own security after 13 years of foreign occupation.
International Security Assistance Force troops will remain in an advisory and mentoring role only while the British will operate the Officer Training Academy outside Kabul, nicknamed Sandhurst-in-the-Sand.
Special Forces soldiers will continue to operate in the country.
This is Mr Cameron’s eighth visit to Afghanistan as Prime Minister and his last with British troops in a combat role.
All British forces will have left Afghanistan by the end of the year, with the exception of a few hundred who will remain for the training mission.
The Prime Minister paid tribute to the 453 UK servicemen and women who have died in the course of operations in the country as well as to those who had been injured.
“We should remember those who paid the ultimate price and those who were injured through the work they did.”