Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

go - How to use linux environment variable in cgo to load shared library

Using cgo to load a shared library in linux.

I want to build a environment to load shared library by linux env path in cgo. But it doesn't work.

My source code tree as below

tree
.
├── inc
│?? └── mylib.h
├── libmylib.so
├── main.go
├── mylib.o
└── src
    └── mylib.c

src/mylib.c

#include <stdio.h>

void PrintHello()
{
    printf("Hello
");
}

inc/mylib.h

void PrintHello();

main.go

package main

/*
#cgo linux CFLAGS: -I${LIB_PATH}/inc
#cgo linux LDFLAGS: -lmylib
#cgo linux LDFLAGS: -L${LIB_PATH}/cgo
#include "mylib.h"
*/
import "C"

func main() {
        C.PrintHello()
}

Compile shared library

gcc -fPIC -c src/mylib.c
gcc -shared mylib.o -o libmylib.so

Set the env.

export LIB_PATH=/home/bill/project/cgo
export LD_LIBRARY_PATH=/home/bill/project/cgo

run the code, but it doesn't work. It seems that cgo can't find the ${LIB_PATH}.

go run main.go
/home/bill/project/cgo/main.go: malformed #cgo argument: -I${LIB_PATH}/inc

I had try to no environment variable "LIB_PATH" is ok.

package main

/*
#cgo linux CFLAGS: -I/home/bill/project/cgo/inc
#cgo linux LDFLAGS: -lmylib
#cgo linux LDFLAGS: -L/home/bill/project/cgo
#include "mylib.h"
*/
import "C"

func main() {
        C.PrintHello()
}
go run main.go
Hello

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...