'Bazel C++ how to include a library that needs to be cloned from github then build before it can be linked?

The library I need to use is: https://github.com/madler/zlib .

To install it separately, I can do:

git clone https://github.com/madler/zlib
cd zlib
make 

Then I can use it during compilation by including "-lz" flag, such as:

g++ -o main main.cpp std=c++17 -lz

I want to make "install zlib and build" a part of my bazel build, instead of asking a user to clone and build zlib manually.

My Bazel build file is as follow:

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

cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
    copts = ["-std=c++17","-O3"],
    linkopts = ["-lz"]
)

What should I add so that when I run "bazel build ...", zlib is also cloned and installed (make)?

Edit: hello-world.cc program to test compilation:

#include <ctime>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <optional>
#include <vector>
#include <zlib.h>

class GzReader {
 private:
  static constexpr int BUFFER_SIZE = 1 << 20;
  const std::string filename_;
  gzFile file_;
  char *buffer_;
  int line_size_, idx_, last_idx_;                                          
  bool finished_;
  size_t line_count_;

 public:
  GzReader() = delete;

  explicit GzReader(std::string filename) : filename_(filename) {
    file_ = gzopen(filename_.c_str(), "r");
    if (!file_) {
      throw std::runtime_error("Could not open file");
    }

    buffer_ = new char[BUFFER_SIZE + 1];
    line_count_ = 0;
    idx_ = 0;
    last_idx_ = 0;
    line_size_ = gzread(file_, buffer_, BUFFER_SIZE);
    buffer_[line_size_] = '\0';
    finished_ = (line_size_ == 0);
  }

  ~GzReader() { 
    delete[] buffer_; 
    gzclose(file_); 
  }
};

static const char *file_name = "text.gz";
int main() {
  GzReader reader(file_name);  
  return 0;
}


Solution 1:[1]

Unfortunately Bazel does not have native support for dependencies that don't provide Bazel BUILD files.

You will have to set up your own zlib mirror with bazel wrapping.

Alternatively, there is a library here that makes it possible, but it will require some elbow grease.

They provide an example specifically for zlib.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1