簡要步驟:
1,將c++ 的方法提取到頭文件.h中( )
2,編譯cc(c++)文件為動態鏈接庫so文件 gcc -fPIC -shared hello.c -o libhello.so
3,將頭文件放入include目錄 .so放入lib目錄
4,go程序中指定 CFLAGS 和 LDFLAGS
#cgo CFLAGS: -I ./include
#cgo LDFLAGS: -L .
b -lhello
-Wl,-rpath,/usr/local
b
#cgo LDFLAGS: -L .


5,運行(go 程序的時候)發布時候指定 export LD_LIBRARY_PATH="lib文件所在目錄" (`pwd`)
export LD_LIBRARY_PATH=./lib
目錄結構:
|-project | |-lib | | |-libhello.so | |-include | | |-hello.h | |-src | | |-main.go | |-pkg | |-bin
編譯為so文件
g++ -g -Wall -lssl -lcrypto -c decrypter.cc -fPIC -shared -o libdecrypter.so
go文件:
package main /* #cgo CFLAGS: -I ./include #cgo LDFLAGS: -L ./lib -lhello #include "hello.h" */ import "C" func main() { C.hello(C.CString("call C hello func")) }
hello.c
#include "hello.h" #include <stdio.h> void hello(const char *str) { printf("%s(%d): %s\n", __FUNCTION__, __LINE__, str); }
hello.h
#ifndef ___HELLO___ #define __HELLO___ void hello(const char *str); #endif
編譯: go build main.go
編譯如果出錯:
# command-line-arguments
/tmp/go-build471704263/command-line-arguments/_obj/xx.cgo2.o: In function `_cgo_7f644bb4ca7c_Cfunc_xxxx':
請一定檢查so文件是否為libxxx.so
編譯如果報錯 could not determine kind of name for C.xxx
請檢查 import "C" 是不是緊挨着 go頂部頭文件c++ 部分注釋代碼
運行: ./main
運行如果出現: error while loading shared libraries: xxx.so: cannot open shared object file: No such file or directory
請一定要 export LD_LIBRARY_PATH="動態鏈接文件所在目錄"
其他說明:golang的注釋中直接寫函數內容的方式只支持c不支持C++
package main //!!!!以下為c代碼不支持c++ /*
#include <stdio.h> #include <stdlib.h> #include <unistd.h> void hello(const char *str) { printf("===> %s(%d): %s\n", __FUNCTION__, __LINE__, str); } */ import "C" func main() { C.hello(C.CString("call C hello func")) }
參考文章:golang的cgo支持調用C++的方法
http://doumadou.github.io/golangdiao-yong-ccfang-fa.html (需要步驟五才能運行成功)
附件:下載