LoginSignup
3
2

More than 5 years have passed since last update.

Visual Studio Code のスニペットでインクルードガードを作ってみる

Posted at

C/C++ でヘッダファイルを作るときにインクルードガードを付ける必要がありますが、わざわざそのために VSCode の拡張機能をインストールしたくない、と思ったので VSCode のスニペット機能の紹介を兼ねて作ってみました。

スニペットの追加方法から説明すると、
1. メニューの ファイル(F)→基本設定(P)→ユーザースニペット(S) を開く
2. "cpp (C++)" を開く
3. 以下のように入力して保存する

{
    // Place your snippets for cpp here. Each snippet is defined under a snippet name and has a prefix, body and 
    // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
    // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
    // same ids are connected.
    // Example:
    // "Print to console": {
    //  "prefix": "log",
    //  "body": [
    //      "console.log('$1');",
    //      "$2"
    //  ],
    //  "description": "Log output to console"
    // }
    ↓この部分を追加する
    "Include Guard": {
        "prefix": "guard",
        "body": [
            "#ifndef $1",
            "#define $1",
            "#endif // $1"
        ]
    }
}

これで追加できました。

使い方は、ヘッダファイルを新規作成して、言語モードがC++になっていることを確認し、guardと入力すると、(大抵は途中の gua くらいで)入力補完ウィンドウにInclude Guard (ユーザースニペット) と表示されます。補完キー (Ctrl+Space) を押しても良いです。
2018-10-19.png
それを選択 (Enter) すると、3行のプリプロセッサが挿入され、3箇所(スニペットの定義で$1と記述した部分)にカーソルが当たった状態になります。
2018-10-19 (1).png
あとは好きなマクロ名を入力すればOKです。
2018-10-19 (2).png
ここで気づいたと思いますが、ファイル名からマクロ名を自動生成などはしませんので悪しからず。そこまで高機能なものが欲しければ拡張機能などを探してください!

ここまでで、C++だけに追加しましたが、必要であればCのスニペットファイルにも同様に追加してください。
「グローバルスニペットファイル」に追加しておけば言語を問わず使用できますが、他の言語のファイルを編集中に誤爆しても困りますので、私は言語ごとのスニペットファイルに追加しました。

3
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2