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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…