Windows under GCC compile C program calls Golang Static Library and C dynamic Library

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Compiling Golang Static Library

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 () {}

compiling static libraries and header files using commands

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

2. Writing a dynamic library of C

Demo.h

int foo ();
int bar ();

Demo.c

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

int foo () {
int a[3] = {n/a};
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

The demo.so dynamic library file is generated

3. C Entry Program Compilation

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;
}

Copy the Golang static library file and the header file to the C folder

Execute GCC command

>gcc-v test.c-o test1 Main.a demo.so-lwinmm-lntdll-lws2_32

Run Test1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.