govisual-studio-codeclangcgo

How to set cgo env variable before vscode launch code?


I have golang code like:


import (
    "github.com/bobertlo/go-mpg123/mpg123"
)

func main() {
    ...
}

From terminal, to build this code. I must set below env variable:

export C_INCLUDE_PATH=$C_INCLUDE_PATH:/opt/homebrew/Cellar/mpg123/1.32.3/include 
export LIBRARY_PATH=$LIBRARY_PATH:/opt/homebrew/Cellar/mpg123/1.32.3/lib

Now I want build using vscode. I configure the launch.json, tasks.json below:

// launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Package",
            "type": "go",
            "request": "launch",
            "mode": "auto",
            "preLaunchTask": "Set CGO_CFLAGS",
            "program": "${fileDirname}"
        }
    ]
}
// tasks.json
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Set C_INCLUDE_PATH",
            "type": "shell",
            "command": "export C_INCLUDE_PATH=$C_INCLUDE_PATH:/opt/homebrew/Cellar/mpg123/1.32.3/include",
            "problemMatcher": []
        },
        {
            "label": "Set LIBRARY_PATH",
            "type": "shell",
            "command": "export LIBRARY_PATH=$LIBRARY_PATH:/opt/homebrew/Cellar/mpg123/1.32.3/lib",
        },
        {
            "label": "Set CGO_CFLAGS",
            "type": "shell",
            "dependsOn":["Set C_INCLUDE_PATH", "Set LIBRARY_PATH"],
            "dependsOrder": "sequence",
        },
    ]
}

But it didn't work. It reports:

Build Error: go build -o /Users/xxx/Projects/portauio-go/examples/__debug_bin2329559837 -gcflags all=-N -l .
# github.com/bobertlo/go-mpg123/mpg123
../../../../go/pkg/mod/github.com/bobertlo/go-mpg123@v0.0.0-20211210004329-c83f21a0fd39/mpg123/mpg123.go:8:10: fatal error: 'mpg123.h' file not found
#include <mpg123.h>
         ^~~~~~~~~~
1 error generated. (exit status 1)

How can I make it work?


Solution

  • I suppose it's because the task type was set to "shell". That means it will execute in another shell, and the env it set won't take effect in the current shell.

    In launch.json, I added env like this, and now it works:

    {
        "name": "Launch mp3.go",
        "type": "go",
        "request": "launch",
        "mode": "auto",
        "program": "examples/mp3.go",
        "args": ["sample-12s.mp3"],
        "env": {
            "CPATH": "${CPATH}:/opt/homebrew/Cellar/mpg123/1.32.3/include",
            "LIBRARY_PATH": "${LIBRARY_PATH}:/opt/homebrew/Cellar/mpg123/1.32.3/lib"
        }
    },