Vowing to shift the "single-minded" US focus from Iraq to al-Qaeda strongholds in Pakistan and Afghanistan, Obama said the war in Iraq "distracts us from every threat that we face and so many opportunities we could seize".
"By any measure, our single-minded and open-ended focus on Iraq is not a sound strategy for keeping America safe.," he said, ahead of next week's visit to Iraq and Afghanistan.
"If another attack on our homeland comes, it will likely come from the same region where 9/11 was planned. And yet today, we have five times more troops in Iraq than Afghanistan," he said, criticising both George Bush, the US president, and McCain, his Republican opponent, over their Iraq strategies.
McCain, however, said that early troop withdrawals from Iraq would squander the success of last year's troop surge strategy and could lead to chaos in the fragile country.
Obama "has it exactly backwards," McCain said.
In a speech delivered at Albuquerque, New Mexico, McCain said the troop increase strategies used in Iraq should also be applied to Afghanistan and that he knows more than Obama about "how to win wars".
McCain said: "When I'm commander-in-chief, there will be nowhere terrorists can run and hide".
PJ Crowley, Obama's campaign adviser, later told Al Jazeera: "Since he started his campaign two years ago, events have evolved in Iraq and elsewhere in the world and it's certainly understandable that candidates will adapt and refine their positions as they get closer to election day."
Abdullah Schliefer, a journalism professor from the American University in Cairo, said: "It was very important for Obama to speak with great clarity on the issue of Iraq because he's been under accusation from the Republicans on this issue, especially before he makes his trip to the Middle East he had to make a very clear statement."
Schleifer said Obama's position over Iraq would find backers in the Arab world as well as in Europe. "I think it will be appreciated in America as well".