Friday, November 19, 2021

[Golang] Golang with Cgo 動態連結(dynamic linking) 與 靜態連結(static linking)函式庫範例與筆記 in Windows environment

This post is focusd on how to do dynamic/static linking using Golang with cgo on Windows environment. If you want to see it on Linux environment, please check out another post: 

[Golang] Golang with Cgo 動態連結(dynamic linking) 函式庫範例與筆記 in Linux environment

First of all, thanks to someone who had posted several useful articles describing how to do dynamic linking and static linking using Golang(Go) with Cgo in Windows environment as follows:

P.S: For using this example on Linux environment, you should deal with the build process for the static and dynamic libraries.

在 Windows 環境建置動態連結函式庫 (Dynamic-link library),使用 MinGW gcc/g++ 以及 CodeBlock

Go with Cgo 靜態連結 (static linking) 函式庫建置範例與筆記
Go with Cgo 動態連結 (dynamic linking) 函式庫建置範例與筆記


https://github.com/teyenliu/win-shared-example

But, the source codes mentioned in these articles are not consistent and not runnable. Due to this situation, I provide a well-prepared sample code in Github which is very convenient for users to get it run and verify. Here you go: 

Please git clone this repository and follow the steps to try:

1. Open the project using Code::Blocks


2. Select: Project --> Properties --> Build targets:

You can choose which kind of library you want to build: Dynamic library or Static library


3. Build the project and you can see the library file in bin\Debug


4. Go build the main.go

dynamic link:

> go build -ldflags -v -x -installsuffix cgo -o example.exe .

static link :

> go build -ldflags="-extldflags '-static -lstdc++'" -o example_static.exe .


5. Execute the example.exe or example_static.exe, and it works as follows:


Also can refer to this another example:
https://github.com/fananchong/test_cgo_sharedlib


P.S:
When I try to cross-compile this project on Linux to the target: Windows, I encounter an error as follows:
/usr/bin/x86_64-w64-mingw32-ld: cannot find -lstdc++
collect2: error: ld returned 1 exit status
exit status 2

And this error seems to related with these:
Bug 23573 "Too many open files" and binutils 2.31.1-1
Bug#930978: /usr/bin/x86_64-w64-mingw32-ld: Linker fails with "too many open files"





No comments: