[英]Build and run Go using cgo using bazel
此 頁面上有一個簡單的 cgo 項目。 它依賴於預構建的 c 共享庫,並且在使用go build
時效果很好,只需稍作更改即可構建。
我想用 Bazel 做同樣的事情。
使用的源代碼與此github 鏈接上的相同,不使用 hello.c 文件。 總而言之,最終代碼如下所示。
/*
* person.c
* Copyright (C) 2019 Tim Hughes
*
* Distributed under terms of the MIT license.
*/
#include <stdlib.h>
#include "person.h"
APerson *get_person(const char *name, const char *long_name)
{
APerson *fmt = malloc(sizeof(APerson));
fmt->name = name;
fmt->long_name = long_name;
return fmt;
};
/*
* person.h
* Copyright (C) 2019 Tim Hughes
*
* Distributed under terms of the MIT license.
*/
#ifndef PERSON_H
#define PERSON_H
typedef struct APerson
{
const char *name;
const char *long_name;
} APerson;
APerson *get_person(const char *name, const char *long_name);
#endif /* !PERSON_H */
package main
/*
#cgo CFLAGS: -g -Wall
#cgo LDFLAGS: -L. -lperson
#include "person.h"
*/
import "C"
import (
"github.com/kubernetes/klog"
)
type (
Person C.struct_APerson
)
func GetPerson(name string, long_name string) *Person {
return (*Person)(C.get_person(C.CString(name), C.CString(long_name)))
}
func main() {
klog.Info("it is running")
var f *Person
f = GetPerson("tim", "tim hughes")
klog.Infof("Hello Go world: My name is %s, %s.\n", C.GoString(f.name), C.GoString(f.long_name))
}
Bazel 構建文件如下。
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
go_library(
name = "listing_lib",
srcs = [
"person.c",
"person.h",
"runner.go",
],
cgo = True,
clinkopts = ["-Lpersons/listing -lperson"],
copts = ["-g -Wall"],
importpath = "github.com/example/project/persons/listing",
visibility = ["//visibility:private"],
deps = ["@com_github_kubernetes_klog//:klog"],
)
go_binary(
name = "listing",
embed = [":listing_lib"],
visibility = ["//visibility:public"],
)
仍然在通過運行bazelisk build //persons/listing
時,會發生錯誤,這是一般的 linker 錯誤。
/usr/bin/ld.gold: error: cannot find -lperson
collect2: error: ld returned 1 exit status
compilepkg: error running subcommand /usr/bin/gcc: exit status 1
我需要一些東西來清理。
-L.
如果構建的 lib 與 go 文件的文件夾相同,則不起作用? 假設 bazel 在源文件夾中看不到庫,但在錯誤的位置查找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.