11# Rust + Golang
22---
33
4- This repository shows how, by combining
5- [ ` cgo ` ] ( https://blog.golang.org/c-go-cgo ) and
6- [ Rust's FFI capabilities] ( https://doc.rust-lang.org/book/ffi.html ) , we can call
4+ This repository shows how, by combining [ ` cgo ` ] ( https://blog.golang.org/c-go-cgo )
5+ and [ Rust's FFI capabilities] ( https://doc.rust-lang.org/book/ffi.html ) , we can call
76Rust code from Golang.
87
9- Run ` make build ` and then ` ./main ` to see ` Rust ` + ` Golang ` in action. You
10- should see ` Hello John Smith! ` printed to ` stdout ` .
8+ Run ` make build-all ` and then ` make run-all ` to see ` Rust ` + ` Golang ` in action,
9+ building and running two binaries, one where the Rust lib is compiled to a shared
10+ lib, and one to a static lib. You should see some log output printed to stderr and
11+ then ` Hello John Smith! ` printed to ` stdout ` . This results in the binaries
12+ ` main_shared ` and ` main_static ` which you can run. See [ Makefile] ( Makefile ) in
13+ this repository for more useful make targets.
1114
1215## You can do this for your own project
1316Begin by creating a ` lib ` directory, where you will keep your Rust libraries.
@@ -19,6 +22,8 @@ types that you used.
1922All that is left to do is to add some ` cgo ` -specific comments to your Golang
2023code. These comments tell ` cgo ` where to find the library and its headers.
2124
25+ For importing a shared lib into your go code, the following must go along with an
26+ additional option given to ` go build ` (see Makefile):
2227``` go
2328/*
2429#cgo LDFLAGS: -L./lib -lhello
@@ -27,7 +32,15 @@ code. These comments tell `cgo` where to find the library and its headers.
2732import " C"
2833```
2934
30- > There should not be a newline between ` */ ` and ` import "C" ` .
35+ For a static lib, the additional ` -ldl ` is necessary compared to the shared
36+ lib, presumably because in the shared lib linking, ` dl ` is linked in some other way
37+ by the magic of shared libs. To import a static lib into your go code:
38+ ```
39+ /*
40+ #cgo LDFLAGS: ./lib/libhello.a -ldl
41+ #include "./lib/hello.h"
42+ */
43+ import "C"
44+ ```
3145
32- A simple ` make build ` (use the [ Makefile] ( Makefile ) in this repository) will
33- result in a binary that loads your dynamic library.
46+ > There should not be a newline between ` */ ` and ` import "C" ` .
0 commit comments