Skip to content

Instantly share code, notes, and snippets.

@rodnaxel
Last active August 24, 2021 16:45
Show Gist options
  • Save rodnaxel/76fb7aeacca278a013537023296524c8 to your computer and use it in GitHub Desktop.
Save rodnaxel/76fb7aeacca278a013537023296524c8 to your computer and use it in GitHub Desktop.
Initialize C/Cpp project for VSCode (only Linux)
#! /usr/bin/env python3
import argparse
import sys
import os, os.path
import subprocess
import json
# Template tasks (use to compile)
tasks = {
"version": "2.0.0",
"windows": {
"options": {
"shell": {
"executable": "cmd.exe",
"args": [
"/C",
"\"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/Tools/VsDevCmd.bat\"",
"&&"
]
}
}
},
"tasks": [
{
"type": "cppbuild",
"label": "g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${workspaceFolder}/src/*.cpp",
"-o",
"${workspaceFolder}/bin/${fileBasenameNoExtension}",
"-I",
"${workspaceFolder}/include/"
],
"options": {
"cwd": "/usr/bin"
},
"problemMatcher": [
"$gcc"
],
"detail": "compiler: /usr/bin/g++"
},
{
"type": "shell",
"label": "MSVC-x64-2019 build active file",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/Fo:",
"${workspaceFolder}\\bin\\",
"/Fe:",
"${workspaceFolder}\\bin\\${fileBasenameNoExtension}.exe",
"${workspaceFolder}\\src\\*.cpp"
],
"problemMatcher": [
"$msCompile"
],
"group": {
"kind": "build",
"isDefault": True
}
}
]
}
# Template launch (use to debuuger)
launch = {
"version": "0.2.0",
"configurations": [
{
"name": "Debug g++ - build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/${fileBasenameNoExtension}.out",
"args": [],
"stopAtEntry": False,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": False,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": True
}
],
"preLaunchTask": "g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
},
{
"name": "Debug MSVC-x64-2019 - build and debug active file",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}\\bin\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": False,
"cwd": "${workspaceFolder}",
"environment": [],
"console": "internalConsole",
"preLaunchTask": "MSVC-x64-2019 build active file"
}
]
}
# Template settings c_cpp_properties
c_cpp_properties = {
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu11",
"cppStandard": "gnu++14",
"intelliSenseMode": "gcc-x64"
},
{
"name": "Win32",
"includePath": ["${workspaceFolder}/**"],
"defines": ["_DEBUG", "UNICODE", "_UNICODE"],
"windowsSdkVersion": "10.0.18362.0",
"compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.24.28314/bin/Hostx64/x64/cl.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "msvc-x64"
}
],
"version": 4
}
main_template = """#include <iostream>
int main() {
// Let's go!
std::cout << "It's you project!" << std::endl;
return 0;
}
"""
clear_template = """
del *.obj
del *.pdb
del .\\bin\\*.exe
del .\\bin\\*.ilk
del .\\bin\\*.pdb
del .\\bin\\*.obj
"""
project_structure = {
'simple': ('bin', 'src', '.vscode'),
'extended': ('bin', 'doc', 'include', 'lib', 'src', 'test', '.vscode')
}
# Command line interface
parser = argparse.ArgumentParser(description="Configure c/cpp project for Visual Studio Code")
parser.add_argument('--name', type=str, required=True, help='project name')
parser.add_argument('--simple', dest='simple', action='store_true', default=False, help='simple project structure')
parser.add_argument('--git', dest='git', action='store_true', default=False, help='use system control version')
args = parser.parse_args()
BASE = os.path.abspath(os.path.dirname(__file__))
PROJECT_NAME = args.name
def create_project_structure():
directories = project_structure['simple'] if args.simple else project_structure['extended']
for directory in directories:
os.makedirs(os.path.join(BASE, PROJECT_NAME, directory))
def create_startup_files():
path = os.path.join(BASE, PROJECT_NAME, "src")
filename = os.path.join(path, "main.cpp")
with open(filename, "w", encoding="utf8") as f:
f.write(main_template)
def create_vscode_files():
names = ('tasks.json', 'launch.json', 'c_cpp_properties.json')
settings = (tasks, launch, c_cpp_properties)
path = os.path.join(BASE, PROJECT_NAME)
for name, config in zip(names, settings):
with open(os.path.join(path, '.vscode', name), "w") as f:
json.dump(config, f, indent=4)
def create_util_files():
if sys.platform == "linux":
with open(os.path.join(PROJECT_NAME, 'clear.sh'), "w") as f:
f.write("rm -rf bin/*")
else:
path = os.path.join(BASE, PROJECT_NAME)
with open(os.path.join(path, 'clear.bat'), "w") as f:
f.write(clear_template)
def check_dependencies():
dependencies = ['gcc', 'gdb', 'cmake', 'code']
no_installed = []
for package in dependencies:
try:
subprocess.run([package, '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
except FileNotFoundError as e:
no_installed.append(package)
if no_installed:
print('Warning! You need install <{}> package'.format(no_installed))
def main():
if os.path.exists(PROJECT_NAME):
raise SystemExit("This projects is exists. Please choose other name!")
create_project_structure()
create_startup_files()
create_vscode_files()
create_util_files()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment