将nlohmann/json构建为Bazel库不会带来任何需要构建的错误

2022-08-21 00:00:00 bazel c++ nlohmann-json

我有一个非常简单的Bazel项目,我试图在其中添加https://github.com/nlohmann/json作为依赖项。为此,我在本地克隆了json存储库,并在存储库的根目录中添加了一个BUILD文件,以生成包含单个包含json.hpp文件的cc_library。但当我构建它时,它总是抱怨没有什么可构建的。

├── json
│?? ├── BUILD
│?? ├── // all files under nlohmann/json repo.
├── myproject
│?? ├── BUILD
│?? └── Main.cpp
└── WORKSPACE

json/Build:

cc_library(
    name = "json",
    hdrs = ["single_include/nlohmann/json.hpp"],
    includes = ["json"],
    visibility = ["//visibility:public"],
)

生成上述代码成功,但没有生成库。注意输出中的"(Nothing To Build)"消息。

bazel build :json
INFO: Analyzed target //json:json (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //json:json up-to-date (nothing to build)
INFO: Elapsed time: 0.065s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action

myproject/Main.cpp:

#include <single_include/nlohmann/json.hpp>

int main() {
    ...
}

myproject/Build:

cc_binary(
  name = "main",
  srcs = ["Main.cpp"],
  deps = [ "//json:json"]
)

myproject生成错误:

myproject/Main.cpp:1:44: fatal error: single_include/nlohmann/json.hpp: No such file or directory
compilation terminated.

你知道我在这里错过了什么吗?我的目标是将json存储库作为我的Bazel项目myproject中的依赖项使用。


解决方案

最好使用http_repository/git_repository机制来获取外部依赖项,因为它们不会扰乱Repo的历史记录,更容易更新,甚至不会被获取,如果您不构建任何依赖于它的东西。

# /WORKSPACE file
http_archive(
    name = "com_github_nlohmann_json",
    build_file = "//third_party:json.BUILD", # see below
    sha256 = "4cf0df69731494668bdd6460ed8cb269b68de9c19ad8c27abc24cd72605b2d5b",
    strip_prefix = "json-3.9.1",
    urls = ["https://github.com/nlohmann/json/archive/v3.9.1.tar.gz"],
)

# /third_party/json.BUILD file
package(default_visibility = ["//visibility:public"])

load("@rules_cc//cc:defs.bzl", "cc_library")

licenses(["notice"]) # MIT license

cc_library(
    name = "json",
    hdrs = ["single_include/nlohmann/json.hpp"],
    strip_include_prefix = "single_include/",
)

然后:

cc_binary(
  name = "main",
  srcs = ["Main.cpp"],
  deps = [ "@com_github_nlohmann_json//:json"]
)
// Main.cpp file
#include "nlohmann/json.hpp"

相关文章