Skip to content

Instantly share code, notes, and snippets.

@IS-KH
Created October 24, 2017 07:43
Show Gist options
  • Save IS-KH/ceeb20ec0a2f157d0b71b753764b7b10 to your computer and use it in GitHub Desktop.
Save IS-KH/ceeb20ec0a2f157d0b71b753764b7b10 to your computer and use it in GitHub Desktop.
example.md
  • This requires a C cross-compiler for ARM. In most cases, it's only available in Linux.
  • Follow steps here to install the GO compiler/toolset first.
  • cross compile a GO program mixed with C. specify the CC as the C cross compiler of your target platform
CGO_ENABLED=1 CC=arm-linux-gnueabihf-gcc  GOARCH=arm GOARM=7 GOOS=linux go build -o hellowithc hellowithc.go # for Cortex A7/A8/A9
CGO_ENABLED=1 CC=arm-mv5sft-linux-gnueabi-gcc  GOARCH=arm GOARM=5 GOOS=linux go build -o hellowithc hellowithc.go # for Marvell Poncat

Simple case: Just a bit C code placed in a comment block of GO

  • hellowithc.go
package main

/*
#include <stdio.h>
#include <stdlib.h>

void myprint(char* s) {
    printf("%s", s);
}
*/
import "C"
import "fmt"

func main() {
  cs := C.CString("Hello from stdio\n")
  C.myprint(cs)
  fmt.Println("done")
}
  • please note there must be no blank lines between import "C" and the above C code in comment block

Complicated case: static link with a external lib(.a)

  • All C sources must be compileed with -fPIC option
  • Add the options for linker in ex. #cgo LDFLAGS: -L. -lphy

example project

  • phyrw.h
#ifndef __PHYRW_H__
#define __PHYRW_H__

void phyopen( char *s, int phyId);
int phyread( int reg);
void phywrite( int reg, int val);
void phyclose();
    
#endif
  • the main go program
/*
#cgo LDFLAGS:  -L. -lphy
#include "./phyrw.h"
*/

/*
#cgo LDFLAGS:  -L. -lphy
#include "./phyrw.h"
*/
import "C"

func PhyOpen(ifname string, phyad int) {
    C.phyopen(C.CString(ifname), C.int(phyad))
}

func PhyRead(reg int) int {
    return int(C.phyread(C.int(reg)))
}

func PhyWrite(reg int, val int) {
    C.phywrite(C.int(reg), C.int(val))
}

func PhyClose() {
    C.phyclose()
}
  • the Makefile
phyrw.o: phyrw.c
  $(CC) -fpic -c -o $@ $<

libphy.a: phyrw.o
  arm-linux-gnueabihf-ar cr $@ $<

tinycore: tinycore.go libphy.a
  CGO_ENABLED=1 CC=$(CC) GOARCH=arm GOARM=7 GOOS=linux go build -o $@  $<
  $(STRIP) $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment