Call c-static-lib in Go

How to compile and call a C-static lib in Golang

touch some files first

1
2
3
# create a directory for this project
mkdir -p ./hi/lib; cd ./hi
touch ./main.go ./lib/hi.h ./lib/hi.c

Create a header file: hi.h

1
2
3
4
5
6
7
#ifndef HI_H
#define HI_H

void print_hi();

#endif // HI_H

Create a source file: hi.c

1
2
3
4
5
6
#include <stdio.h>

void print_hi() {
printf("hi, from C\n");
}

Create a main file: main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

/*
#cgo CFLAGS: -I ${SRCDIR}/lib
#cgo LDFLAGS: -L ${SRCDIR}/lib -l hi
#include "hi.h"
*/
import "C"

func main() {
C.print_hi()
}

Compile the source file into a static library

1
2
gcc -c ./lib/hi.c -o ./lib/hi.o
ar rcs ./lib/libhi.a ./lib/hi.o

Run

1
2
3
4
5
# go run directly
go run main.go

# or build and run
go build -o bin/hi main.go && ./bin/hi

FYI

Source Code