Onyz
Onyz

Reputation: 9

Issue with cross-compiling when using CGO and conditional compilation

I'm working on a cross-platform Go project, and everything works fine on Windows, but I run into issues when building on Linux (via WSL) or darwin. Here’s the relevant code:

Practice/internal/io/write.go

package io

import (
    "Practice/pkg/sysio"
)

func Write() error {
    sysio.HelloWorld()
    HelloFromC()

    return nil
}

Practice/internal/io/constants.go

//go:build linux || darwin || windows
// +build linux darwin windows

package io

/*
#include <stdio.h>
#include <stdlib.h>

void hello() {
    printf("Hello from C!\n");
}
*/
import "C"
import "fmt"

func HelloFromC() {
    fmt.Println("Calling C function from Go:")
    C.hello() // Call the C function
}

Practice/pkg/sysio/sysio_unix.go

//go:build linux || darwin
// +build linux darwin

package sysio

import "fmt"

func HelloWorld() {
    fmt.Println("Hello from linux/darwin")
}

Practice/pkg/sysio/sysio_windows.go

//go:build windows
// +build windows

package sysio

import "fmt"

func HelloWorld() {
    fmt.Println("Hello from windows")
}

The issue

On Windows (my machine): The project builds and runs fine, no errors.

On VSCode: It displays this error in Practice/internal/io/write.go: undefined: HelloFromC [darwin]

On Linux (WSL): I get the following error when building: ./write.go:12:2: undefined: HelloFromC The error indicates that the HelloFromC function is not recognized when building on Linux, even though I have the go:build constraints in place for both Windows and Linux in the constants.go file.

The confusion: When I remove the conditional build constraints from the sysio package (e.g., having one HelloWorld function without build constraints), it works fine, even though I expect the constraints in sysio to be isolated to that package.

My questions

Why does this code fail to build on Linux, even with go:build linux || darwin || windows in constants.go?

Why does removing build constraints in the sysio package make it work, even though these constraints should only apply to their respective files?

Upvotes: -1

Views: 60

Answers (0)

Related Questions