Turbocharge Visual Studio Code with Snippets for C++ Coding
Coding can often involve repetitive tasks which can become time-consuming and mundane over time. Fortunately, modern text editors like Visual Studio Code offer the facility to create custom snippets. These are templates that make it easier to insert repeating code patterns.
Step 1: Launch Visual Studio Code
First, open Visual Studio Code on your computer.
Step 2: Open ‘Configure User Snippets’
Go to File
> Preferences
> Configure User Snippets
in the application’s top toolbar. Alternatively, use the Command Palette (Ctrl+Shift+P
or Cmd+Shift+P
on macOS), type “Preferences: Configure User Snippets”, and select it.
Step 3: Select Your Language’s Snippets File
A search bar will appear. Type “cpp” and select the file named cpp.json
.
Step 4: Prepare Your Snippets File
To create a new snippet, delete all existing content in the cpp.json
file. You should now have an empty file.
Step 5: Create Your Snippet
Now, paste the following code snippet directly into the empty cpp.json
file:
{
"cpp snippets": {
"prefix": "basicfile",
"body": [
"// $TM_FILENAME",
"// author-name $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE",
"// file-description",
"",
"#include <iostream>",
"using namespace std;",
"",
"int main()",
"{",
" return 0;",
"}"
],
"description": "c++ basic file template"
}
}
This is a simple, yet powerful example. The code block creates a C++ snippet identified by the keyword basicfile
which generates a skeleton for a basic C++ file.
NOTE: Thanks to Alex C. for the automatic file name and date.
Step 6: Save and Close the File
Once you’ve pasted the snippet, save and close the cpp.json
file. With everything saved, your snippet is ready for use!
Step 7: Test Your New Snippet
To try out your new snippet, open a new C++ file in Visual Studio Code, type basicfile
, and hit ENTER
. Like magic, your C++ skeleton is populated in your file.
In Summary
It really is that simple. You’ve now created a custom C++ snippet in Visual Studio Code! The next time you need to generate a basic template for your C++ file, remember to use your custom snippet to save time and maintain standardized code formatting.
Happy coding! 🎉