hankeyyh
hankeyyh

Reputation: 133

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/[email protected]/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?

Upvotes: 1

Views: 132

Answers (2)

hankeyyh
hankeyyh

Reputation: 133

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"
    }
},

Upvotes: 1

talha
talha

Reputation: 21

Can ${env:ENV_VAR} variable references be what you are looking for? This is workspace specific.

However there are specific settings for go extention as well.

Upvotes: 0

Related Questions