Windows 下GCC編譯C程式調用Golang靜態庫和C動態庫

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

 

1. 編譯golang 靜態庫

package mainimport (    "C"    "fmt")//export Foofunc Foo(a, b int) int {    return a + b}//export Barfunc Bar() {    fmt.Println("Hello, I'm LiLei.")}func main() {}

使用命令編譯得到靜態庫和標頭檔

go build -o main.a -buildmode=c-archive main.go

2. 編寫C的動態庫

demo.h

int foo();
int bar();

demo.c

#include "demo.h"
#include <stdio.h>

int foo(){
    int a[3] = {1,2,3};
    int s = 0;
    int len = sizeof(a)/sizeof(a[0]);
    printf("len=%d\n", len);
    for(int i=0; i<len;i++){
            s+=a[i];
    }    
    printf("calc s=%d\n", s);
    return s;
}

int bar(){
        printf("hello, I am Lilei");
        return 32;
}

gcc -shared -fpic -o demo.so demo.c

會產生demo.so動態庫檔案

 

3. C 入口程式編譯

test.c

#include "demo.h"
#include "main.h"
#include <stdio.h>

int main(){
    foo();
    bar();
    Bar();
    GoInt32 a=3;
    GoInt32 b=4;
    GoInt s = Foo(a,b);
    printf("s=%d\n", s);
    return 0;
}

將GOlang 靜態庫檔案和標頭檔複製到C檔案夾下

執行GCC 命令

>gcc -v test.c -o test1 main.a demo.so -lWinMM -lntdll -lWS2_32

運行test1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.