golang調用c++檔案

來源:互聯網
上載者:User

標籤: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++檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.