This is a creation in Article, where the information may have evolved or changed.
dlv debug
The command compiles and debugs one package
, with the following code:
func debugCmd(cmd *cobra.Command, args []string) { status := func() int { var pkg string dlvArgs, targetArgs := splitArgs(cmd, args) if len(dlvArgs) > 0 { pkg = args[0] } err := gobuild(debugname, pkg) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) return 1 } fp, err := filepath.Abs("./" + debugname) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) return 1 } defer os.Remove(fp) processArgs := append([]string{"./" + debugname}, targetArgs...) return execute(0, processArgs, conf) }() os.Exit(status)}
Where the gobuild
function is implemented as follows:
func gobuild(debugname, pkg string) error { args := []string{"-gcflags", "-N -l", "-o", debugname} if BuildFlags != "" { args = append(args, BuildFlags) } args = append(args, pkg) return gocommand("build", args...)}
dlv debug
The command is actually a temporary compilation in the current directory to generate an executable without code optimization, the file name is debug
. The next step is execute
to invoke the function to debug
debug the file. dlv
after the program exits, the file is deleted: defer os.Remove(fp)
.