The macro journey begins here, moving a function from a header file into its source file. The first problem presents itself as this: how can I get at the source file from the header file?

I have never known why this functionality has not been present in Visual Studio, perhaps it is harder than it appears! Still, Visual Assist has managed it, and a few people seem to want it. So, let’s add it!

The easiest thing to do is to take the filename in full, check if it ends in .cpp or .h, and then replace with .h or .cpp to get the paired source file. This is basically what the following code does (more or less based on the code found here):

Private Function GetCorrespondingFilename(ByRef currentFilename As String) As String
    Dim correspondingFilename As String

    If (currentFilename.EndsWith("cpp", StringComparison.InvariantCultureIgnoreCase)) Then
        correspondingFilename = Left(currentFilename, Len(currentFilename) - 3) + "h"
    ElseIf (currentFilename.EndsWith_
	("h", StringComparison.InvariantCultureIgnoreCase)) Then
        correspondingFilename = Left(currentFilename, Len(currentFilename) - 1) + "cpp"
    End If

    Return correspondingFilename

End Function

This does have a few limitations though: what if the header is a .hpp file? What if the cpp file is cxx or c? What if the header and source files live in different folder locations?
These are all very interesting questions that I am going to ignore for now and go for the simplest case. Your headers and source live in the same folder (I am assuming). You use rigorous .h and .cpp naming standards for your header and source files respectively. Ah, life is easy.

Where I will deviate from the linked post is how we open the document. The original open method can be slow if you have many files open in Visual Studio, and if the file does not exist it will be created. Which can be nice, but not usually what we want. Here is the function to get the corresponding source file and open it.

Public Sub ToggleBetweenHeaderAndSource()
    If (ActiveDocument Is Nothing) Then
    End If

    Dim otherFilename = GetCorrespondingFilename(ActiveDocument.FullName)
    If FileIO.FileSystem.FileExists(FileName) Then
        Application.Documents.Open(otherFilename, "Text")
    End If
End Sub

We check that ActiveDocument Is Nothing because the nasty errors that Visual Studio throws at us when we run this macro with no file open aren’t very nice. We then get the corresponding filename and open it if it exists. Great!

We’ll be building on this macro next time to automatically generate an empty function body in the source file, all from the header definition. That is when things really get interesting.

Download macro - 632 B

Can you improve upon this macro? Leave your suggestions and comments below!


推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架