0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WSL + C/C++でのデバッグで変数のウォッチができない問題の対処法

Posted at

はじめに

最近になってAtCoderを触りはじめました。AtCoderにはコードテストがあるためわざわざ環境構築をする必要はありませんが、やはり使い慣れたエディタ上で作成をしたいものです。
Visual Studio 2022を使うことも考えましたが、ソースコードの管理の点で使いにくいと感じたため、Visual Studio Codeを使用しています。
言語は既に環境構築をしているPythonを使用していましたが、C/C++を使おうとして環境構築で躓いたため備忘録として本記事を書きます。

環境構築

環境構築は以下の記事を参照しました。この記事の通りにやれば一通りできると思います。
私は Windows10 + VSCode + WSLの環境で構築しました。

問題発生

テストコードも動かせることだし実際にコードを作成してみようと思いデバッグを始めた所で問題に気がつきました。
image.png
ブレイクポイントが設定されている時点で既にNや配列への入力は済んでいるため、画面左側の変数>Locals に表示されているはずです。しかし、何も表示されておらず、これでは Visual Studio 2022 の代わりとしてのエディタにはなれません。
なんとかして問題を解決する必要が出てきました。

解決策

色々と弄ってみた結果、問題はtask.jsonにありました。環境構築の手順に従って作成した時点で以下のようになっていました。

task.json
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "/usr/bin/g++",
            "args": [
                "-std=gnu++17",
                "-Wall",
                "-Wextra",
                "-O2",
                "-g",
                "-fsanitize=address,undefined",
                "-I${workspaceFolder}/ac-library",
                "-o",
                "${workspaceFolder}/program",
                "'${file}'",
            ],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "silent",
                "focus": false,
                "panel": "shared",
                "showReuseMessage": false,
                "clear": true
            },
        }
    ]
}

問題は、"arg"で渡している最適化オプション("-O2")にありました。最適化は高速化を図ることが出来ますが、その反面として今回のような意図しない結果を産んだと思われます。
なのでこのオプションを最適化を行わない"-O0"に書き換えます。

"args": [
    "-std=gnu++17",
    "-Wall",
    "-Wextra",
-    "-O2",
+    "-O0",
    "-g",
    "-fsanitize=address,undefined",
    "-I${workspaceFolder}/ac-library",
    "-o",
    "${workspaceFolder}/program",
    "'${file}'",
],

これで無事想定通りに動きました。
image.png

おわりに

Visual StudioでC/C++を使っていた時は、最適化がデバッグ時に問題を引き起こすということがなかったので、今までいい感じにエディタがやっていてくれていたのかなと思いました。
また余談ですが、ネットで調べてもデバッグのやり方を書いた記事が多く出てきたものの、解決方法を見つけることは難しかったです。この記事が今後誰かの役に立てばいいなと思います。

本記事について誤字脱字や語弊などがありましたら、指摘して頂けると幸いです。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?