[Solved] unable to set CGO_ENABLED=1 – Go

by
Ali Hasan
algorithm

Quick Fix: Create a batch script (run.bat) with the following contents:

set CGO_ENABLED=1
go run -race .

Then, run the script instead of directly running go run.

The Problem:

Unable to set the CGO_ENABLED environment variable to 1. This is preventing the usage of the -race flag with go run.

The Solutions:

Solution 1: Using a Batch Script

Create a batch script named run.bat with the following contents:

set CGO_ENABLED=1
go run -race .

Execute the batch script to run your code with CGO enabled.

Solution 2: Modifying Environment Variables in Visual Studio Code

Modify the environment variables within a launch script in Visual Studio Code.

  1. Open your project directory in Visual Studio Code.
  2. Create a launch configuration file (e.g., .vscode/launch.json) with the following JSON:
  3. “`json
    {
    “version”: “0.2.0”,
    “configurations”: [
    {
    “name”: “Go (CGO Enabled)”,
    “type”: “go”,
    “request”: “launch”,
    “mode”: “auto”,
    “program”: “${workspaceFolder}/your_main_go_file.go”,
    “env”: {
    “CGO_ENABLED”: “1”
    }
    }
    ]
    }
    “`

  4. Select the “Go (CGO Enabled)” configuration from the debugging dropdown in Visual Studio Code.
  5. Run your code with CGO enabled using the debugger.

Solution 2: Setting CGO_ENABLED Environment Variable

To resolve this issue, follow these steps:

  1. Open a command prompt or terminal.
  2. Set the CGO_ENABLED environment variable using the command:
    go env -w CGO_ENABLED=1

    This command modifies the environment variables for the current Go environment, setting CGO_ENABLED to 1.

  3. Verify the change by running the command:
    go env

    You should see a line like:
    GOENV: CGO_ENABLED=1

If you don’t have a C compiler installed on your system, you may encounter an error message after setting CGO_ENABLED. To install a C compiler, follow these instructions for your operating system from the Visual Studio Code documentation:

Q&A

How can I set CGO_ENABLED environment variable to 1 in Visual Studio Code?

Create a batch script run.bat to run your code with set CGO_ENABLED=1 and go run -race . commands

What will happen if I don’t have C compiler installed while setting CGO_ENABLED?

You will get the error: cgo: C compiler "gcc" not found

Video Explanation:

The following video, titled "Building Go Executables: The cgo / Docker Problem - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

@MikiTebeka shows us how cgo can create some roadblocks with our Alpine Docker image and how to solve them. ... Set cgo_enabled=0 in order to tell ...