簡體   English   中英

使用 cgo 使用 bazel 構建並運行 Go

[英]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

我需要一些東西來清理。

  • c 庫是自動構建的嗎? 我的假設是那些不是。
  • 如果不是,那為什么是-L. 如果構建的 lib 與 go 文件的文件夾相同,則不起作用? 假設 bazel 在源文件夾中看不到庫,但在錯誤的位置查找。
  • 是否可以使用 cc_library 規則來構建可在 cgo 中使用的共享庫? 如果是這樣,如何連接這些?

c 庫是自動構建的嗎? 我的假設是那些不是。

為什么? 來自官方 repo 的測試顯示,它是自動完成

是否可以使用 cc_library 規則來構建可在 cgo 中使用的共享庫? 如果是這樣,如何連接這些?

這里查看示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM