標籤:lag str c++ 函數 stdio.h 編譯 title ring can
簡要步驟:
1,將c++ 的方法提取到標頭檔.h中( )
2,編譯cc(c++)檔案為動態連結程式庫so檔案
3,將標頭檔放入include目錄 .so放入lib目錄
4,go程式中指定 CFLAGS 和 LDFLAGS
#cgo CFLAGS: -I ./include
#cgo LDFLAGS: -L .b -lhello -Wl,-rpath,/usr/localb
5,運行發布時候指定 export LD_LIBRARY_PATH="lib檔案所在目錄" (`pwd`)
目錄結構:
|-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
運行: ./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++的方法
golang之cgo---調用C/C++動態庫函數
http://doumadou.github.io/golangdiao-yong-ccfang-fa.html (需要步驟五才能運行成功)
附件:下載
golang調用c++檔案