Golang 1.21 not exporting functions when using import "C"

78 Views Asked by At

Recently I am trying to upgrade my Go microservice from 1.15 to 1.21.

The code used to work, but now in one of my packages I get this warning: This file is within module "services\\my-service", which is not included in your workspace. To fix this problem, you can add a go.work file that uses this directory.

And I can't see the functions from other packages. However if I remove the import "C" line from the code, the warning goes away and the functions are successfully exported, but of course I can't call C functions from my Go code.

Does anyone know what happened and how I can fix it? Thank you.

My folder structure looks like this:

/services
 - (other, independent micro-services, not written in Go)
 - /my-service
   - Dockerfile
   - go.mod
   - go.sum
   - main.go
   - /routes
     - model.go
     - router.go
   - /sdk
     - /include --> .h files
     - /libs --> .so files
     - types.go
     - invoice.go

Having something like this in the types.go file:

package sdk

import (
    "sync"
)

type client struct {
    ... // simple structs
}

and invoice.go:

package sdk

/*
#cgo CFLAGS: -I${SRCDIR}/sdk/include
#cgo linux,386 LDFLAGS: -L${SRCDIR}/libs -ldinvoicesdk
#include <stdlib.h>
#include "include/invoices.h"
*/

import "C"
import (
    "errors"
    "log"
    "strconv"
    "unsafe"
)

const (
    invalidToken int = 0
    timeoutMs    int = 1000
)

func Initialize() {
    C.Invoice_Initialize(0)
    log.Printf("Initialize - invoice native client initialized\n")
}

I can't see the Initialize function from outside the module, it says that it is undefined. If I remove the import "C" statement, it can find it but of course I cannot call native C code. This worked perfectly in version 1.15 (although I didn't use go.mod files).

These are the go.mod and go.sum files:

module inv

go 1.21.6

require github.com/gorilla/mux v1.8.1
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=

And this would be the main.go:

package main

import (
    "log"
    "net/http"
    "inv/routes"
    "inv/sdk"
)

func main() {
    log.SetFlags(log.LstdFlags | log.Lshortfile)
    sdk.Initialize() --> this is undefined

    router := routes.NewRouter()
    http.ListenAndServe(":80", router)
}
0

There are 0 best solutions below