Skip to content

Instantly share code, notes, and snippets.

@fasionchan
Created February 12, 2022 09:43
Show Gist options
  • Save fasionchan/f58b6ae9efc89008cb129debe093a9f0 to your computer and use it in GitHub Desktop.
Save fasionchan/f58b6ae9efc89008cb129debe093a9f0 to your computer and use it in GitHub Desktop.
Call C function in Go | Go语言调用C函数
#include <stdio.h>
#include "callee.h"
void SayHello() {
printf("Hello, world!\n");
}
void SayHello();
package main
/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lcallee
#include "callee.h"
*/
import "C"
import (
"fmt"
)
func main() {
C.SayHello()
fmt.Println("Success!")
}
.DEFAULT_GOAL := run
callee.o: callee.c
gcc -fPIC -c callee.c
libcallee.so: callee.o
gcc -shared -o $@ $^
caller: caller.go libcallee.so
go build caller.go
clean:
rm -f caller libcallee.so callee.o
run: caller
./caller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment