cgo and Python as a shared library

320 views
Skip to first unread message

Deiter

unread,
Nov 23, 2022, 9:48:25 PM11/23/22
to golang-nuts
macOS: 12.5.1
go: go1.19.3 darwin/amd64

I'm having trouble building a go module that uses Python as a shared library.

This code works:
...
package main

// #include <float.h>
import "C"
import "fmt"

func main() {
fmt.Println("Max float value of float is", C.FLT_MAX)
}
...
$ go run .
Max float value of float is 3.4028234663852886e+38
...
I run into problems when I try to include Python:
...
package main

/*
#cgo pkg-config: python3
#cgo LDFLAGS: -lpython3.8
*/
import "C"

import (
"fmt"
)

func main() {
C.Py_Initialize()
fmt.Println(C.GoString(C.Py_GetVersion()))
C.Py_Finalize()
}
...
$ go run .
# producer
./producer.go:16:2: could not determine kind of name for C.Py_Finalize
./producer.go:15:25: could not determine kind of name for C.Py_GetVersion
./producer.go:14:2: could not determine kind of name for C.Py_Initialize
...

Any suggestions? I'm guessing it has something to do w/ setting PKG_CONFIG_PATH and/or CGO_CFLAGS but I'm not certain...

Deiter

unread,
Nov 23, 2022, 9:59:44 PM11/23/22
to golang-nuts
Doh! I forgot the include. I get a linker error now:
...
package main

/*
#cgo pkg-config: python3
#cgo LDFLAGS: -lpython3.8
#include <Python.h>
*/
import "C"

import (
"fmt"
)

func main() {
C.Py_Initialize()
fmt.Println(C.GoString(C.Py_GetVersion()))
C.Py_Finalize()
}
...
$ go run .
# producer
/usr/local/go/pkg/tool/darwin_amd64/link: running clang failed: exit status 1
ld: library not found for -lpython3.8
clang: error: linker command failed with exit code 1 (use -v to see invocation)
...
Clearly a library is missing but I'm not clear where to find it or how to inform the linker. Thanks.

Howard Waterfall

unread,
Nov 26, 2022, 3:23:09 PM11/26/22
to golang-nuts
SOLVED!
It took a while to sort out the various locations.

Environment Variables:
....
export LIBRARY_PATH=/usr/local/Frameworks/Python.framework/Versions/3.9/lib
export PKG_CONFIG_PATH=/usr/local/Frameworks/Python.framework/Versions/3.9/lib/pkgconfig
....

Code:
...
package main

/*
#cgo pkg-config: python3
#cgo CFLAGS: -I/usr/local/Frameworks/Python.framework/Headers
#cgo LDFLAGS: -L/usr/local/Frameworks/Python.framework/Versions/3.9/lib -lpython3.9 -ldl -framework CoreFoundation

#include <Python.h>
*/
import "C"

import (
"fmt"
)

func main() {
C.Py_Initialize()
fmt.Println(C.GoString(C.Py_GetVersion()))
C.Py_Finalize()
}
...




--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/d1b70059-0a25-4fbb-bcd9-9b133592cbe5n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages