Quick toggle between .h and .cpp files
When programming C++ it is a very common need to switch between the .h and .cpp file. There are no built in way to do this in Visual Studio, however it is possible to accomplish! You can either use an expensive helper program, such as Visual Assist or you can do it freely by writing a macro.
To write a macro that switch between the source and header file is easy, here is a step-by-step guide for Visual Studio 2005.
Creating the macro
- Start Visual Studio 2005
- Go into ‘Tools->Macros->Macros IDE‘
- Right click on ‘My Macros’ and select ‘Add->Add New Item’
- Select ‘Module’ and name it ‘ToggleCPPH’ and click on ‘Add’
- Select the newly created module and paste this into it
- Save the macro and switch back to the Visual Studio 2005 IDE.
Public Module ToggleCPPH Sub Toggle()
Dim fileName As String = DTE.ActiveDocument.Name
If (fileName.EndsWith(".cpp")) Then
fileName = fileName.Remove(fileName.IndexOf(".")) + ".h"
Else
fileName = fileName.Remove(fileName.IndexOf(".")) + ".cpp"
End If
DTE.ExecuteCommand("File.OpenFile", DTE.ActiveDocument.Path + fileName)
End Sub
End Module
Assigning the toggle macro to a shortcut key
- Click on ‘Tools->Options’ and select ‘Keyboard’.
- Select your C++ keyboard mapping scheme and type ‘macro’ in the ‘Show commands containing:’ field. Note, if you can’t see the macro in the list, try to restart Visual Studio.
- Select the ToggleCPPH macro and assign in the some convincing shortcut keys.
- Click on ‘Assign’.
- Click on ‘Ok’.
Testing the toggle macro
- Open an .h or .cpp file in Visual Studio.
- Press the shortcut keys and snap – you are now hopefully in the corresponding header or source file!
Notes
This is a very simple macro, no error handling has been implemented. If no corresponding .h or .cpp file exists a message box will show up and say no such file exists – in many cases this is good enough. If you are using a lot of other files (e.g. .inl) you may want to add that into the toggle chain. I am not sure how to do this, you will have to check if it exists before trying to open it. I will leave this as an exercise to you. If you find a solution, please don’t hesitate to post it in the comments below!
Keep the coding up!