编程笔记

lifelong learning & practice makes perfect

vscode|go测试调试配置

单测

在vscode中,带_test的go源文件里的测试函数有有专门的优化,可点击”run test”,”debug test”一键测试

配置

在settings.json可以指定go buld参数如ldfalgs,gcflags等

1
2
3
4
5
6
7
8
9
10
"go.buildFlags": [
"--ldflags -r=${workspaceRoot}/lib" // works for 'debug test' but not 'run test'
// "-ldflags=-r ${workspaceRoot}/lib" // works for 'run test' but not 'debug test'
],
"go.buildTags": "linux",
"gopls": {
"build.buildFlags": [
"-tags=linux",
]
}

在2023.10.27使用go1.21和最新的vscode,gopls遇到一个问题,”run test”,”debug test”对ldflags参数解析行为不一致
可参考如上配置

1
2
3
"go.buildFlags": [
"--ldflags=-r=${workspaceRoot}/clib"
],

2023.11.3测试上面这个可用,参考issue

项目debug

launch.json

在左侧的debug添加配置如下,buildFlags指定go build参数,debug模式必须传–gcflags=’all=-N -l’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "GO:Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceRoot}",
"buildFlags": "--gcflags='all=-N -l' --ldflags='-r ./lib'"
}
]
}

也可使用launch.json配合tasks.json,通过tasks定义任务构建项目生成可执行文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
// exec: debug a precompiled binary
// The binary must be built with go build -gcflags=all="-N -l" to disable inlining and optimizations that can interfere with debugging.
{
"name": "UC:Debug",
"type": "go",
"request": "launch",
"mode": "exec",
"asRoot": true,
"program": "${workspaceRoot}/program",
"console": "integratedTerminal",
"preLaunchTask": "go: build (debug)"
},
]
}

tasks.json,label指定任务名称,在launch.json中通过preLaunchTask指定在debug前需要执行的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"version": "2.0.0",
"tasks": [
{
"label": "go: build (debug)",
"type": "shell",
"command": "go",
"args": [
"build",
"-gcflags=all=-N -l",
"-ldflags=-r ./lib",
"-tags=linux",
"-o",
"${workspaceRoot}/program"
],
"options": {
"cwd": "${workspaceRoot}"
},
}
]
}

欢迎关注我的其它发布渠道