Search code examples
c++bazelnlohmann-json

Building nlohmann/json as a bazel library gives 'nothing to build' error


I have a very simple bazel project where I'm trying to add https://github.com/nlohmann/json as a dependency. To accomplish that, I cloned the json repo locally and added a BUILD file in the repo's root dir to generate a cc_library containing the single include json.hpp file. But when I build that, it always complains that there is nothing to build.

├── 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"],
)

Building the above succeeds but there is no library generated. Notice '(nothing to build)' message in the output.

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 Build error:

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

Any ideas what am I missing here? My goal is to consume the json repo as a dependency in my bazel project myproject.


Solution

  • It is better to fetch external dependencies using http_repository/git_repository mechanism, because they do not clutter the history of the repo, they are easier to update and they are not even fetched, if you do not build anything, which depends on it.

    # /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/",
    )
    

    And then:

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