我使用以下 main.go 调用 cpp lib 所以
package main
/*
#cgo LDFLAGS: -L/home/roroco/Dropbox/cpp/cpp_lib/draft/go_call_cpp -lprogress
#include "progress_lib.h"
// Callback function to be called from C++
extern void progressCallback(int progress);
*/
import "C"
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
//export progressCallback
func progressCallback(progress C.int) {
fmt.Printf("Progress: %d%%\n", progress)
if progress == 100 {
wg.Done()
}
}
func main() {
wg.Add(1)
go func() {
C.do_work(C.progress_callback(C.progressCallback))
}()
wg.Wait()
}
当我第一次导出 LD_LIBRARY_PATH 然后运行代码时,代码运行良好
~/Dropbox/cpp/cpp_lib/draft/go_call_cpp $ export LD_LIBRARY_PATH=/home/roroco/Dropbox/cpp/cpp_lib/draft/go_call_cpp:$LD_LIBRARY_PATH
~/Dropbox/cpp/cpp_lib/draft/go_call_cpp $ go run main.go
Progress: 0%
Progress: 10%
当我直接运行代码时,它会引发错误:
~/Dropbox/cpp/cpp_lib/draft/go_call_cpp $ go run main.go
/tmp/go-build2581226776/b001/exe/main: error while loading shared libraries: libprogress.so: cannot open shared object file: No such file or directory
exit status 127
我希望不要在cli中导出LD_LIBRARY_PATH,而是将export LD_LIBRARY_PATH放在我的main.go中,我该怎么办?
我使用-Wl,-rpath代替导出LD_LIBRARY_PATH,以下是完整代码
package main
/*
#cgo CFLAGS: -I${SRCDIR}
#cgo LDFLAGS: -L${SRCDIR} -lprogress -Wl,-rpath,${SRCDIR}
#include "progress_lib.h"
// Callback function to be called from C++
extern void progressCallback(int progress);
*/
import "C"
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
//export progressCallback
func progressCallback(progress C.int) {
fmt.Printf("Progress: %d%%\n", progress)
if progress == 100 {
wg.Done()
}
}
func main() {
wg.Add(1)
go func() {
C.do_work(C.progress_callback(C.progressCallback))
}()
wg.Wait()
}