vscodeでC言語を扱っています。GO言語の場合TABキーでネストを自動的に揃えてくれるのですが、現状のvscodeでC言語では上手くできません。方法を教えて下さい。
VSCodeでC言語のインデントをGo言語のようにTABキーで自動的に整える方法を説明します。
1. C/C++拡張機能をインストール
まず、MicrosoftのC/C++拡張機能がインストールされているか確認してください。
- VSCodeの「拡張機能」 (
Ctrl+Shift+X
) で「C/C++」を検索 ms-vscode.cpptools
をインストール
2. settings.json
を作成
.vscode
フォルダの中に settings.json
を作成します。
方法1: VSCodeのGUIを使う
.vscode
フォルダ内で 右クリック → 新しいファイル- ファイル名を
settings.json
にする
3. settings.json
に設定を追加
作成した settings.json
を開いて、以下の内容を記述します。
{
"editor.formatOnType": true, // セミコロンや波括弧入力時に自動フォーマット
"editor.formatOnSave": true, // 保存時に自動フォーマット
"editor.tabSize": 4, // タブ幅を4に設定
"editor.insertSpaces": false, // タブをスペースに変換しない
"C_Cpp.clang_format_fallbackStyle": "Google",
"C_Cpp.clang_format_style": "{ BasedOnStyle: Google, IndentWidth: 4, UseTab: Always }"
}
4. Emacsキーバインドを使いつつTABの動作を変更
Emacsのキーバインドを保持したままTABの動作だけ修正したい場合、keybindings.json
でTABキーの挙動を変更できます。
設定方法
Ctrl+Shift+P
で 「Preferences: Open Keyboard Shortcuts (JSON)」 を検索keybindings.json
を開く- 以下の設定を追加:
[ { "key": "tab", "command": "editor.action.reindentlines", "when": "editorTextFocus" } ]
これで、私の環境の方では何とか動いたようです。
[.vscode/c_cpp_properties.json]
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**",
"C:/msys64/mingw64/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.22621.0",
"compilerPath": "C:/msys64/mingw64/bin/gcc.exe",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
[.vscode/launch.json]
{
"version": "0.2.0",
"configurations": [
{
"name": "Cデバッグ (MinGW64)",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "gdb を有効化",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"miDebuggerPath": "C:/msys64/mingw64/bin/gdb.exe"
}
]
}
[.vscode/settings.json]
{
"editor.formatOnType": true, // セミコロンや波括弧入力時に自動フォーマット
"editor.formatOnSave": true, // 保存時に自動フォーマット
"editor.tabSize": 4, // タブ幅を4に設定
"editor.insertSpaces": false, // タブをスペースに変換しない
"C_Cpp.clang_format_fallbackStyle": "Google",
"C_Cpp.clang_format_style": "{ BasedOnStyle: Google, IndentWidth: 4, UseTab: Always }"
}
[.vscode/tasks.json]
{
"version": "2.0.0",
"tasks": [
{
"label": "Cコンパイル (MinGW64)",
"type": "shell",
"command": "C:/msys64/mingw64/bin/gcc",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.exe"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$gcc"
],
"detail": "MSYS2 MinGW64 の GCC を使用して C をコンパイル"
}
]
}
作成したCファイルをアクティブにし、Ctrl + Shift + B を押してビルドタスクを実行したあと、vscodeのデバッグができるようです。