此页面上有简单的 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_Htypedef 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"],)我需要一些事情来清除。c库是自动构建的吗?我的假设是,这些都不是。如果不是,那么如果构建的lib与go文件是同一文件夹,那么为什么不工作?假设 bazel 在源文件夹中看不到库,但在错误的位置查找。-L.是否可以使用cc_library规则来构建可在 cgo 中使用的共享库?如果是这样,如何连接它们?
- 1 回答
- 0 关注
- 150 浏览
添加回答
举报
0/150
提交
取消