Starting a new C++ project at 42 involves creating many classes.
Each class requires creating two files (.hpp and .cpp), adding standard boilerplate code (like header guards, includes, the "Canonical Form" functions), declaring member variables, and defining member functions. Doing this manually every time is repetitive, slow, and prone to errors.
This guide shows you how to use a simple Python script and a VS Code task to automate this process, saving you time and ensuring consistency.
The Goal: Create a VS Code command that, when run, asks you for a class name, member variables, and member methods, and then automatically generates the corresponding .hpp and .cpp files with the necessary boilerplate.
How it Works:
-
A Python Script: This script is the core engine. It takes the class name, variable list, and method list as input. It knows the structure of a standard 42 C++ class and generates the text content for both the header (
.hpp) and source (.cpp) files, including the boilerplate, variable declarations/copying, and method definitions. -
A VS Code Task: This is how you trigger the Python script from within VS Code. It defines a custom command in VS Code's Command Palette. When you run this task, VS Code will:
- Prompt you for the required information (class name, variables, methods).
- Execute the Python script, passing your inputs as arguments.
- Show you the script's progress and any messages in the VS Code terminal.
This script contains the logic for generating your C++ code.
- Open your C++ project folder in VS Code.
- Create a new folder named
scriptsat the root level of your project (the same level as yourMakefile). - Inside the
scriptsfolder, create a new file namedcreate_cpp_class.py. - Paste the Python code from my repo into this file.
- Save the file.
What this script does:
- It reads the class name, the variables string, and the methods string provided as command-line arguments.
- It parses the variables string (expected format:
"type1 name1, type2 name2, ...") and methods string (expected format:"ReturnType1 method1(params1), ReturnType2 method2(params2), ...") into structured data. - It constructs the full file paths for the
.hppfile (in anincludedirectory) and the.cppfile (in asrcdirectory). It will create these directories if they don't exist. - It generates the header guard name based on the class name.
- It builds the content for the
.hppfile, including:- The header guard (
#ifndef,#define,#endif). - Basic includes (
iostream,string). - The
class ClassName { ... };declaration. - The canonical form declarations (
Constructor(),CopyConstructor(),operator=,Destructor()). - The variable declarations you provided under
private:. - The method declarations you provided under
public:.
- The header guard (
- It builds the content for the
.cppfile, including:- The
#include "ClassName.hpp". - The basic definitions for the canonical form functions (with comments indicating where to add logic).
- Code within the Copy Assignment Operator (
operator=) to copy the member variables you provided. - Basic function definitions (
ReturnType ClassName::methodName(params) { ... }) for the methods you provided.
- The
- It writes the generated content to the respective
.hppand.cppfiles. - It prints messages to the terminal indicating which files were created or if errors occurred (like the file already existing).
This step is necessary on Unix-like systems (Linux, macOS) so that VS Code can run the script directly.
- Open the integrated terminal in VS Code (
Terminal->New TerminalorCtrl+/Cmd+). - Make sure you are in your project's root directory.
- Run the following command:
This gives the script file permission to be executed like a program. On Windows, running with
chmod +x scripts/create_cpp_class.py
python3command often handles this, but if you encounter permission issues, look into setting execute permissions for scripts on your specific Windows setup.
This tells VS Code how to interact with your script.
- Open the VS Code Command Palette (
Ctrl+Shift+PorCmd+Shift+P). - Type
Tasks: Configure Taskand select it. - Select
Create tasks.json file from template. - Select
Others. This will create a.vscodefolder with atasks.jsonfile if you don't have one already. - Open the
.vscode/tasks.jsonfile. - Replace the default content with the
tasks.jsoncode from my repo. - Save the file.
What this tasks.json configuration does:
- It defines a custom task named
"Create C++ Class (Enhanced)". This is the name you will select in the Command Palette. - It specifies that this task should run a
shellcommand. - The
commandis set to"python3", which tells the shell to use the Python 3 interpreter. (Ifpython3doesn't work on your system, try just"python"). - The
argslist provides the arguments that will be passed to thepython3command:"./scripts/create_cpp_class.py": The first argument is the path to your script."${input:classNameEnhanced}": This special syntax means "get the value from the input prompt defined below with IDclassNameEnhancedand pass it as an argument"."${input:memberVarsEnhanced}": Passes the value from the variables input prompt."${input:memberMethodsEnhanced}": Passes the value from the methods input prompt.
- The
inputssection defines the interactive prompts that VS Code will show you when you run the task:- It defines an input with
id: "classNameEnhanced"that usestype: "promptString"to ask the user thedescription: "Enter C++ class name:". - It defines similar input prompts for member variables and member methods, guiding you on the expected format (e.g.,
"string _name, int _age").
- It defines an input with
Now you're ready to generate classes quickly.
- Open the VS Code Command Palette (
Ctrl+Shift+PorCmd+Shift+P). - Type
Tasks: Run Taskand select it. - A list of available tasks will appear. Select
"Create C++ Class (Enhanced)". - VS Code will display a sequence of input boxes at the top of the window, corresponding to the
inputsdefined in yourtasks.json:- Type the desired class name (e.g.,
Zombie) and press Enter. - Type the member variables in the specified format (e.g.,
std::string _name, int _brainsEaten). Separate multiple variables with commas. Press Enter. You can leave this blank and press Enter if you have no variables to add right now. - Type the member methods in the specified format (e.g.,
void announce(), void eatBrains(int num)). Separate multiple methods with commas. Press Enter. You can leave this blank and press Enter if you have no methods to add right now.
- Type the desired class name (e.g.,
- After you press Enter for the methods, the VS Code terminal panel will open and execute the Python script with your inputs.
- The terminal will show messages indicating that
include/Zombie.hppandsrc/Zombie.cpp(or whatever class name you chose) have been created.
That's it! You have automatically generated the files and the common boilerplate code for your new C++ class using your scripted VS Code environment.
Important Considerations:
- Python 3: Ensure you have Python 3 installed and the
python3command works in your terminal. - Code Location: The script assumes
include/andsrc/directories at your project root. Adjust theheader_dirandsource_dirvariables in the Python script if your structure is different. - Customization: To change the generated boilerplate (add different default includes, change formatting, etc.), you must edit the
create_cpp_class.pyscript itself. Modify the large multiline strings (header_contentandsource_content). - Beyond Boilerplate: Remember, this tool creates the framework. You still need to manually:
- Write the actual logic inside the method bodies (
{...}). - Initialize member variables correctly in your constructors (the script adds comments suggesting where to do this). The script handles copying in the assignment operator, but initializer lists in constructors are often preferred for member initialization.
- Handle complex resources (like raw pointers) that require deep copies or specific cleanup in the canonical form functions.
- Write the actual logic inside the method bodies (
By setting this up, you've successfully "scripted your favorite text editor" (VS Code) to handle a repetitive part of your C++ development workflow, allowing you to focus more on writing the unique logic for each class!