一、直接寫在GO文件中
package main
/*
#include <stdio.h>
void demo(){
printf("HELLO WORLD! \n");
}
*/
import "C"
func main() {
C.demo()
}
構建方式
go build
go build main.go
注: 這種方式只適合代碼量特別小的場景
二、寫在獨立文件中但必須跟main.go文件同一目錄
目錄結構
.
├── README.md
├── demo.c
├── demo.h
└── main.go
main.go
package main
// #include "demo.h"
import "C"
func main() {
C.demo()
}
demo.h
#ifndef DEMO_H_
#define DEMO_H_
void demo(void);
#endif
demo.c
#include "demo.h"
#include <stdio.h>
void demo(){
printf("HELLO WORLD! \n");
}
構建方式
如果指定go文件,go不會自動構建c文件了
go build
注: 這種方式只適合代碼量不算大,幾個文件足夠的服務
三、靜態(tài)庫
目錄結構
.
├── clibs
│ └── demo
│ ├── README.md
│ ├── demo.c
│ ├── demo.h
│ └── main.go
└── main.go
main.go
package main
/*
#cgo CFLAGS: -I./clibs/demo
#cgo LDFLAGS: -L${SRCDIR}/clibs/demo -ldemo
#include "demo.h"
*/
import "C"
func main() {
C.demo()
}
demo.h
#ifndef DEMO_H_
#define DEMO_H_
void demo(void);
#endif
demo.c
#include "demo.h"
#include <stdio.h>
void demo(){
printf("HELLO WORLD! \n");
}
構建方式
cd ./clibs/demo
gcc -c -o demo.o demo.c
ar rcs libdemo.a demo.o
cd ../../
go build
注: 這種方式支持生產(chǎn)環(huán)境服務構建,且可以將c文件打包到服務中不會產(chǎn)生額外的運行時依賴,但是靜態(tài)庫一般包含了全部的代碼,里面會有大量的符號,如果不同靜態(tài)庫之間出現(xiàn)了符號沖突則會導致鏈接的失敗。
四、動態(tài)庫
目錄結構
.
├── clibs
│ └── demo
│ ├── README.md
│ ├── demo.c
│ ├── demo.h
│ └── main.go
└── main.go
main.go
package main
/*
#cgo CFLAGS: -I./clibs/demo
#cgo LDFLAGS: -L${SRCDIR}/clibs/demo -ldemo
#include "demo.h"
*/
import "C"
func main() {
C.demo()
}
demo.h
#ifndef DEMO_H_
#define DEMO_H_
void demo(void);
#endif
demo.c
#include "demo.h"
#include <stdio.h>
void demo(){
printf("HELLO WORLD! \n");
}
構建方式
cd ./clibs/demo
gcc -shared -o libnumber.so number.c
cd ../../
go build