Visual Studio Code を使った C++ プログラミング 〜フォーマッターとインデクサー〜
毎回プロジェクトが変わるたびに検索して設定している気がするので,まとめておきます.
インデクサーの設定
インデクサーには GNU Global を使います.Ubuntu 16.04 の時は apt でちょうどいいバージョンをインストールすることができず,ソースをダウンロード&ビルドしていたんですが,Ubuntu 18.04 の場合はそのままダウンロードすれば OK でした.
1. GNU Global のダウンロード
sudo apt install global
3. vscode の再起動
一応再起動しておきます.
4. GNU Global による GTAG の作成
ctrl + alt + P でコマンドパレットを開き,"Global: Rebuild Gtags Database" を選択.
ここまで来れば,ジャンプしたいメソッドやクラス名にカーソルを合わせて F12 を押下すれば,該当のソース・ヘッダに飛んでくれると思います.
フォーマッターの設定
次にフォーマッターの設定です.ここでは,Clang-Format を使います.clang-format としてデフォルトでインストールされるソフトのバージョンが古い場合が結構あり,ハマりポイントなので,ちょっと新しめの clang-format をインストールします.
1. clang-format のダウンロード
今回は clang-format-6.0 をインストールしました.
sudo apt install clang-format-6.0
2. vscode の Extensions から,Clang-Format をダウンロード
3. vscode の再起動
一応再起動しておきます.
4. settings.json の設定
{ "editor.defaultFormatter": "xaver.clang-format", "clang-format.executable": "/usr/bin/clang-format-7", "clang-format.language.cpp.style": "{ BasedOnStyle: Google, IndentWidth: 2, ColumnLimit: 80, DerivePointerAlignment: false, PointerAlignment: Left }", "[cpp]": { "editor.tabSize": 2 }, "editor.formatOnSave": true }
細かい設定は,下記のブログに解説付きで書いてくれてました!が,vscode の extension が全部対応してない可能性もあるような気がします.
yasuharu519.hatenablog.com
上記の設定をすると,
Before
#includenamespace test_test_test { namespace hoge_hoge_hoge { void test_hoge_func(const char *p); } } void test_test_test::hoge_hoge_hoge::test_hoge_func(const char *p) {} #include int main() { std::cout << "Hello World" << std::endl; return 0; }
After
#includenamespace test_test_test { namespace hoge_hoge_hoge { void test_hoge_func(const char* p); } } // namespace test_test_test void test_test_test::hoge_hoge_hoge:: test_hoge_func(const char* p) {} #include int main() { std::cout << "Hello World" << std::endl; return 0; }
な感じになります.PointerAlignment の設定がちょっとハマったのですが,Google の Style で DerivePointerAlignment が true になっているようなので,これを明示的に false にする必要がありました.