建立巨集

回報問題 查看來源 Nightly · 8.4 · 8.3 · 8.2 · 8.1 · 8.0 · 7.6

假設您需要在建構過程中執行工具。舉例來說,您可能想產生或預先處理來源檔案,或是壓縮二進位檔。在本教學課程中,您將建立可調整圖片大小的巨集。

巨集適合用於簡單的工作。如要執行更複雜的操作 (例如新增對新程式設計語言的支援),請考慮建立規則。規則可讓您進一步控管及調整。

如要建立可調整圖片大小的巨集,最簡單的方法是使用 genrule

genrule(
    name = "logo_miniature",
    srcs = ["logo.png"],
    outs = ["small_logo.png"],
    cmd = "convert $< -resize 100x100 $@",
)

cc_binary(
    name = "my_app",
    srcs = ["my_app.cc"],
    data = [":logo_miniature"],
)

如果需要調整更多圖片的大小,建議重複使用程式碼。如要這麼做,請在個別的 .bzl 檔案中定義函式,並呼叫 miniature.bzl 檔案:

def miniature(name, src, size="100x100", **kwargs):
  """Create a miniature of the src image.

  The generated file is prefixed with 'small_'.
  """
  native.genrule(
    name = name,
    srcs = [src],
    outs = ["small_" + src],
    cmd = "convert $< -resize " + size + " $@",
    **kwargs
  )

注意事項:

  • 按照慣例,巨集會像規則一樣,具有 name 引數。

  • 如要記錄巨集的行為,請使用 docstring,就像在 Python 中一樣。

  • 如要呼叫 genrule 或任何其他原生規則,請使用 native.

  • 使用 **kwargs 將額外引數轉送至基礎 genrule (運作方式與 Python 相同)。這項功能非常實用,使用者可以運用 visibilitytags 等標準屬性。

現在,請使用 BUILD 檔案中的巨集:

load("//path/to:miniature.bzl", "miniature")

miniature(
    name = "logo_miniature",
    src = "image.png",
)

cc_binary(
    name = "my_app",
    srcs = ["my_app.cc"],
    data = [":logo_miniature"],
)