Working with cgo

Trying to do my first steps with cgo at Win10, so I read this and this and this and made the below:

C:/cgo> go mod init hasan/lib
C:/cgo> code .

main.go

package main

import "C"
import "fmt"

//export HelloWorld
func HelloWorld() {
	fmt.Printf("hello world")
}

func main() {}

Compiled it as:

C:/cgo> go build -buildmode=c-shared
C:/cgo> dir
 Directory of C:\cgo

06/06/2020  02:23 PM    <DIR>          .
06/06/2020  02:23 PM    <DIR>          ..
06/06/2020  01:41 PM                26 go.mod
06/06/2020  02:23 PM         3,503,249 lib
06/06/2020  02:23 PM             1,580 lib.h
06/06/2020  01:42 PM               170 main.go
               4 File(s)      3,505,025 bytes

The created another module into another directory cgotest created go file named hello.go and copied both lib and lib.h into it:

C:/cgotest> dir
 Directory of C:\cgotest

06/06/2020  02:18 PM    <DIR>          .
06/06/2020  02:18 PM    <DIR>          ..
06/06/2020  02:17 PM                24 go.mod
06/06/2020  02:18 PM               134 hello.go
06/06/2020  02:18 PM         3,503,249 lib
06/06/2020  02:18 PM             1,580 lib.h
               4 File(s)      3,504,987 bytes

The hello.go is:

package main

// #cgo CFLAGS: -g -Wall
// #include <stdlib.h>
// #include "lib.h"
import "C"

func main() {
	HelloWorld()
}

And tried to use go run but got error as below:

D:\cgotest>go run .
# lintest
.\hello.go:9:2: undefined: HelloWorld

As far as I remember c imported stuff is in the C package. So it’d be C.HelloWorld()

I got the below error, note I’m working at Win10 laptop.

D:\cgotest>go run .
# lintest
C:\Users\HASAN~1.YOU\AppData\Local\Temp\go-build829713742\b001\_x002.o: In function `_cgo_cd3f93e214f7_Cfunc_HelloWorld':
/tmp/go-build/cgo-gcc-prolog:49: undefined reference to `HelloWorld'
collect2.exe: error: ld returned 1 exit status
# lintest
cgo-gcc-prolog: In function '_cgo_cd3f93e214f7_Cfunc_HelloWorld':
cgo-gcc-prolog:47:49: warning: unused variable '_cgo_a' [-Wunused-variable]

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.