Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...