My question is regarding building mosques on graves. Verse 21 of Sura al-Kahf says: Behold, they dispute among themselves as to their affair. Some said: Construct a building over them. Their Lord knows best about them. Those who prevailed over their affair said: Let us surely build a place of worship over them. (Q 18:21)
Does this ayah, tells us that we can build the mosque on graves of pious people?
It is important to note the difference between "building mosques or places of worship on graves" and "taking graves as mosques or places of worship". The latter, clearly being polytheistic practice, is prohibited in Islam, while the former is not.
On some occasions the Holy Prophet (sws) referred to a certain practice of Christians and Jews of turning the graves of their pious people into places of worship. This practice is contrary to the basic teachings of Islam. Islam does not approve of polytheistic activities in any form. In another tradition the Prophet (sws) is reported to have forbidden Muslims from making his own grave as a place of worship, as was done by the Jews and the Christians.
It should be noted that had it been prohibited to make mosques on graves, the Prophet (sws) would not have agreed upon building the first mosque in Madinah in a place, which was formerly a graveyard.
Building mosques, for worshiping the one True God only, as a memorial for some pious people can by no means be considered as prohibited. This is exactly what those referred to in the Holy Qur'an did after they found out that the people of the cave were pious people, who worshipped the one True God. Thus, they tried to keep their memory alive by building a place of worship of the One True God.