Skip to main content
In the previous example we wrote a simple C program that only prints “hello world” and includes a standard header file. Real programs often use external code/libraries installed via system package manager (apt or brew) and link against it. It’s possible to use Bazel to do the same thing - rather than a “hermetic” build. This isn’t typically what you want, but might be useful during a migration, or for certain fixed development environments. In this example we will write a simple program that reads a file and tries to determine what kind of file it is by using libmagic. Before we do that, we need to install libmagic on our computers.
  • MacOS users can brew install libmagic followed by brew link libmagic
  • Debian users can apt-get install libmagic-dev
  • Windows users can follow along by using Windows Subsystem for Linux (WSL).
Here is an example C program that opens a file and tells the mime type using libmagic. Let’s name this src/magic.c.
Outside of Bazel, compiling this program can be accomplished by running gcc main.c -lmagic -o main where the compiler is told to link against libmagic via -lmagic. Here’s an equivalent Makefile, though note the portability issues with finding the lib and include folders:
❔On macOS -L $(brew --prefix)/lib -I $(brew --prefix)/include flags have to be added to the command line to allow the compiler to find brew managed libraries. On Linux this is not necessary as apt installs everything under system /usr
When compiling on macOS some additional configuration is also needed to allow linking against homebrew managed libraries.
Finally we can create a cc_binary target for our program and run it via bazel run src:magic and should see the Usage: line from earlier.