Use the C language library you wrote in Go with cgo.
The program to be libraryed is hello.c and hello.h is its header file. main.c is a program that uses that library.
hello.c
#include <stdio.h>
#include "hello.h"
void hello(void)
{
printf("Hello, World!\n");
}
hello.h
extern void hello(void);
main.c
#include <stdlib.h>
#include "hello.h"
int main(int argc, char *argv[])
{
hello();
return EXIT_SUCCESS;
}
$ gcc -c hello.c
$ ar rusv libhello.a hello.o
$ gcc -o main main.c -L. -lhello
$ ./main
Hello, World!
I prepared the following program called main.go. cgo is a function for using the C language program provided as standard in Go with Go.
main.go
package main
/*
#cgo LDFLAGS: -L. -lhello
#include <hello.h>
*/
import "C"
func main() {
C.hello()
}
ʻImport Import a package that requires" C "`. The comment out written just above it is the code for using C language.
/*
#cgo LDFLAGS: -L. -lhello
#include <hello.h>
*/
The C language can be written here as it is, and the functions defined here can be used in the Go code. Gives information about the C language library to use at compile time with LDFLAGS, which has the same meaning as the two arguments specified with $ gcc -o main main.c -L. -lhello in the previous chapter. An option where -L specifies the location of the library. The library is libhello.a created in the previous chapter and is under the same directory, so specify only .. -l specifies the library to use, the way to specify is the library name excluding lib, that is, hello excluding lib from libhello. After that, include hello.h so that you can call thehello ()function.
The execution result is as follows.
$ go run main.go
Hello, World!
Recommended Posts