在 visual studio 代码中调试 cgo 产生 "multiple definition of" 错误

debugging cgo in visual studio code produces "multiple definition of" error

我正在尝试用 visual studio 代码调试一个非常简单的 cgo 应用程序,但出现错误。当我 go run main.go 时,应用程序运行良好,没有任何问题。但是当我尝试在 visual studio 代码中使用调试器时,出现以下错误:

# prolink007/simple-cgo
C:\Users\proli\AppData\Local\Temp\go-build964876546\b001\_x003.o: In function `Hello':
./hello.c:4: multiple definition of `Hello'
C:\Users\proli\AppData\Local\Temp\go-build964876546\b001\_x002.o:d:/projects/simple-cgo/main.go:6: first defined here
collect2.exe: error: ld returned 1 exit status
exit status 2
Process exiting with code: 1

这是我的main.go

package main

/*
  #include "hello.c"
*/
import "C"
import (
    "errors"
    "log"
)

func main() {
    err := HelloWorld()
    if err != nil {
        log.Fatal(err)
    }
}

func HelloWorld() error {
    _, err := C.Hello()
    if err != nil {
        return errors.New("error calling Hello function: " + err.Error())
    }

    return nil
}

这是我的hello.c

//hello.c
#include <stdio.h>

void Hello(){
    printf("Hello world\n");
}

这是我的launch.json。

{
    // 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": "Launch",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "program": "${fileDirname}",
            "env": {},
            "args": []
        }
    ]
}

我如何在 visual studio 代码中调试此应用程序或是否有不同的调试方法?

我在 github 上问过同样的问题,得到的答案解决了我的问题。

I have reproducted it on linux.

Can you try go build -gcflags="all=-N -l" ./ with

//#cgo LDFLAGS: -Wl,--allow-multiple-definition 
import "C" 

as described in golang/go#16513 ?