上文我們建立一個local_repository的Bazel項目,實作hello-world函數。我把這個repository放在伺服器上,項目組的其他小夥伴們都不再需要各自重新實作了,直接通過本地檔案系統分享到了我的勞動成果。
大家使用後都贊不絕口,結果一傳十,十傳百,全球各地的開發者紛紛要求能夠直接使用這個項目。本着開源精神,我決定把它放到github上,這樣Bazel在建構時能夠自動調用git指令,将依賴到的repository從github上下載下傳到本地,Bazel提供了git_repository來實作這個功能。
那就開始吧。
先在github上建立一個repository,命名為hello-world-repo,其目錄結構如下:
hello-world-repo/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "hello-world-lib",
srcs = ["src/hello-world.cc"],
hdrs = ["include/hello-world.h"],
visibility = ["//visibility:public"],
)
hello-world-repo/include/hello-world.h
#pragma once
#include <string>
std::string hello_world();
hello-world-repo/src/hello-world.cc
#include "include/hello-world.h"
std::string hello_world() { return "Hello, world!"; }
好了,github上已經搞定了,它靜靜地等着全球各地的開發者下載下傳使用了。
hello-world-git-repo/WORKSPACE
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "hello-world-repo",
remote = "[email protected]:zhouxindong/hello-world-repo.git",
branch = "master",
)
跟上文一樣,我們還是在WORKSPACE中引入git_repository外部依賴,remote和branch指定git repository的位址和分支。
hello-world-git-repo/src/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "hello-world-main",
srcs = ["hello-world-main.cc"],
deps = [
"@hello-world-repo//:hello-world-lib",
],
)
hello-world-git-repo/src/hello-world-main.cc
#include "include/hello-world.h"
#include <iostream>
int main() {
std::cout << hello_world() << std::endl;
return 0;
}
好了,運作一下試試:bazel run //src:hello-world-main
源碼擷取:[email protected]:zhouxindong/bazel-learning.git