Skip to content

Instantly share code, notes, and snippets.

@jason19970210
Last active September 10, 2023 02:16
Show Gist options
  • Select an option

  • Save jason19970210/4b6c4f34bbe90dd366de608f3e9e8f17 to your computer and use it in GitHub Desktop.

Select an option

Save jason19970210/4b6c4f34bbe90dd366de608f3e9e8f17 to your computer and use it in GitHub Desktop.
[Solved] Golang test with cgo for shared object (.so) usage

Solved the problem with Attempt 2 with export LD_LIBRARY_PATH

Environment

## On-Premise
OS: Ubuntu 22.04.2
Golang Ver.: 1.21.0
GCC Ver.: 11.4.0

## Docker
Image: golang:lastest
Golang Ver.: 1.21.1
GCC Ver.: 12.2.0

Tree

## Attempt 1
.
├── go_sum
├── libsum.so
├── main.go
├── README.md
├── sum.c
└── sum.h

## Attempt 2
.
├── go_sum
├── lib
│   ├── libsum.so
│   ├── sum.c
│   └── sum.h
├── main.go
└── README.md

Enable CGO

$ CGO_ENABLED=1

Compile shared object with gcc

$ gcc -shared -o libsum.so sum.c

Compile golang exec

$ go build -o go_sum main.go
$ ./go_sum

Check

## On-Premise
$ ldd go_sum 
    linux-vdso.so.1 (0x00007ffc70e71000)
    libsum.so => not found
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f2aa6373000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f2aa65a4000)

## Docker
$ ldd go_sum 
    linux-vdso.so.1 (0x00007ffd297fa000)
    libsum.so => not found
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8865b7f000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f8865d65000)

Error

$ ./go_sum
./go_sum: error while loading shared libraries: libsum.so: cannot open shared object file: No such file or directory

Solution

Add the LD_LIBRARY_PATH

$ export LD_LIBRARY_PATH=`pwd`/lib/

Ref:

  1. ChatGPT
  2. https://segmentfault.com/q/1010000022621510
  3. https://serverfault.com/a/201711 [*]
package main
/* Select JUST 1 cgo config */
/* Attempt 1 */
/*
#cgo LDFLAGS: -L. -lsum
#include "sum.h"
*/
/* Attempt 2 */
/*
#cgo CFLAGS: -Ilib
#cgo LDFLAGS: -Llib -lsum
#include "sum.h"
*/
import "C"
import "fmt"
func main() {
// Call the sum function from the shared library
result := C.sum(5, 7)
// Print the result
fmt.Printf("Sum: %d\n", result)
}
// sum.c
#include <stdio.h>
#include "sum.h"
int sum(int a, int b) {
return a + b;
}
// sum.h
#include <stdio.h>
int sum(int a, int b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment