首页 > 解决方案 > 如何使用 Bazel 构建这个简单的示例?

问题描述

假设我有一个这样的项目:

$ tree . 
├── WORKSPACE
├── include
│   └── header.hpp
└── main.cpp
└── BUILD.bazel

main.cpp看起来像这样:

#include "header.hpp"

int main() {
  return 0;
}

我的BUILD.bazel文件应该是什么样的?

我目前的尝试:

cc_binary(
  name = "app",
  srcs = [
    "main.cpp",
    "include/header.hpp",
  ],
)

编辑:忘了提及我的WORKSPACE文件


编辑:找到了解决方法,但我认为它不是很优雅:

cc_library(
  name = "app-hdrs",
  hdrs = [
    "include/header.hpp",
  ],
  srcs = [
    "include/header.hpp",
  ],
  strip_include_prefix = "include",
)

cc_binary(
  name = "app",
  srcs = [
    "main.cpp",
  ],
  deps = [
    ":app-hdrs",
  ],
)

标签: c++bazel

解决方案


您需要WORKSPACE在项目文件夹中调用一个文件:

$ tree . 
├── include
│   └── header.hpp
└── main.cpp
└── BUILD.bazel
└── WORKSPACE

然后您可以使用以下命令构建您的应用程序:

bazel build //:app

并在copts-flag 中指定包含路径:

cc_binary(
  name = "app",
  srcs = [
    "main.cpp",
    "include/header.hpp",
  ],
  copts = ["-Iinclude", "-Wall", "-Werror"],
)

cc_binary(
  name = "app",
  includes = [ "include" ],
  srcs = [
    "main.cpp",
    "include/header.hpp",
  ],
  copts = [ "-Wall", "-Werror" ],
)

推荐阅读