Visual Studio 11: C++ IntelliSense Code Snippets

Introduction

One of the new features of Visual Studio 11 is inserting C++ code snippets, i.e. easily adding already made C++ code at a specified insertion point or around a selected block. This is useful and may save programming time when it's necessary to add commonly-used code, for example preprocessor directives (if, else, for, while, switch, try/catch blocks, and so on). Visual Studio 11 comes with a set of C++ code snippets but we can create and use our own, as well.

An Example of Code Often Manually Added

Let's say we have created a Win32 DLL project, which has to export some classes and functions. One common way to include the same header file, containing exported class definitions or exported function declarations, in the DLL and in client modules is using preprocessor definitions as in the following example:

#ifdef MYLIB_EXPORTS
#define MYLIB_EXP __declspec(dllexport)
#else
#define MYLIB_EXP __declspec(dllimport)
#endif

class MYLIB_EXP CFoo {/*...*/};
MYLIB_EXP void foo();

 

If we have to implement many DLL projects, each containing many exported symbols, there is a lot of code that has to be manually added. Of course, copy-pasting then modifying by hand is a solution but the Visual C++ code snippets feature offers a better and faster solution.

Using Code Snippets

Before going further, we have to notice there are two methods to add code snippets:

  • at an insertion point (expansion snippets)
  • around a selected block of code (surround-with snippets)

Next, we demonstrate step-by-step how to use each of the two methods to automate the inserting of the above sample of code.

 

Using an Expansion Snippet

  1. Click in the source editor at the point where you want to insert the code snippet.

    Set Insertion Point
    Figure 1: Set Insertion Point

     

  2. Keeping Ctrl key pressed, push 'K' then 'X'. Alternatively, we can select the "Edit/IntelliSense/Insert Snippet..." menu item.
    A list of available code snippets appears. Select the desired one ("#ifdef") then hit the Enter key.

    Insert Snippet
    Figure 2: Insert Snippet

  3. The inserted code snippet contains a highlighted default name ("DEBUG"), which can be replaced with our desired one.

    Default Code Snippet
    Figure 3: Default Code Snippet

  4. Replace "DEBUG" with "MYLIB_EXPORTS" and hit the Enter key.

    Complete Code
    Figure 4: Complete Code

     

  5. Complete by hand the code betwen "#ifdef" and "#endif"

  6.  

Note: Code snippets may have "shortcuts". In the case of our example, the shortcut is "#ifdef". That means, to insert this snippet we can simply type "#ifdef" in the editor, and then hit the Tab key.

Using a Surround-with Snippet

  1. In the source editor, select code to surround.

    Select Code to Surround
    Figure 5: Select Code to Surround

  2. Keeping the Ctrl key pressed, push 'K' then 'S'. Alternatively, we can select the "Edit/IntelliSense/Surround With..." menu item.
    A list of available code snippets appears. Select the desired one ("#ifdef") then hit the Enter key.

    Surround With
    Figure 6: Surround With

  3. The inserted code snippet contains a highlighted default name ("DEBUG"), which can be replaced with our desired one.

    Default Surround Code
    Figure 7: Default Surround Code

  4. Replace "DEBUG" with "MYLIB_EXPORTS" and hit the Enter key.

    Complete Code
    Figure 8: Complete Code

Quite nice, until now! However, we still have some manually added code. Next page, we create our own code snippet to make all in one shot.

Visual Studio 11: C++ IntelliSense Code Snippets

Creating and Using Our Own Code Snippets

Creating a code snippet is quite easy. First of all we have to write a little XML file following the Code Snippets specifications, which can be found in the MSDN Library. Alternatively, we can use an existing code snippet file as a template. (You can choose one from "..\Microsoft Visual Studio 11.0\VC\Snippets\1033\Visual C++\" folder).
Here are the code snippet file contents that I've created for automated insertion of DLL export preprocessor directives:

 

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
   <CodeSnippet Format="1.0.0">
      <Header>
         <Title>DLL Export Definitions</Title>
         <Shortcut></Shortcut>
         <Description>DLL export preprocessor definitions</Description>
         <Author>Ovidiu Cucu</Author>
         <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
         </SnippetTypes>
      </Header>
      <Snippet>
         <Declarations>
            <Literal>
               <ID>lib_name</ID>
               <ToolTip>Library name</ToolTip>
               <Default>LIB</Default>
            </Literal>
         </Declarations>
         <Code Language="cpp"><![CDATA[#ifdef $lib_name$_EXPORTS
            #define $lib_name$_EXP __declspec(dllexport)
            #else
            #define $lib_name$_EXP __declspec(dllimport)
            #endif]]>
         </Code>
      </Snippet>
   </CodeSnippet>
</CodeSnippets>

 

Save this file with the .snippet extension, let's call it dll_export_definitions.snippet, and then import it into the Visual C++ IDE using Code Snippets Manager tool (see "Tools/Code Snippets Manager..." menu item).

[30-code snippets manager.jpg]
Figure 9: Code Snippets Manager

Finally, let's use it!

  1. Click in Visual C++ editor, hit 'K' then 'X' keeping Ctrl pressed, then choose the DLL Export Definitions code snippet from the list.

    [31-insert my code snippet.jpg]
    Figure 10: Insert My Code Snippet

  2. Replace the default literal ("LIB")...

    [32-replace defaults.jpg]
    Figure 11: Replace Defaults

    ...and voila the final result!

    [33-final result.jpg]
    Figure 12: Final Result

 

Notes

  • We can imagine many other useful code snippets, e.g. for message crackers, mapping user messages in MFC applications, and so on.
  • Code snippets are also supported in older versions of Visual Studio, but not for Visual C++ projects.
  • As of the date of writing this article, Visual Studio 11 Beta is available for free at: Visual Studio 11 Beta downloads

Resources



About the Author

Ovidiu Cucu

Graduated at "Gh. Asachi" Technical University - Iasi, Romania. Programming in C++ using Microsoft technologies since 1995. Microsoft MVP awardee since 2006. Moderator and article reviewer at Codeguru.com, the number one developer site. Co-founder of Codexpert.ro, a website dedicated to Romanian C++ developers.

Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

  • Live Event Date: December 18, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this upcoming webcast …

Most Popular Programming Stories

More for Developers

RSS Feeds