Quick Start
This section briefly introduces how to bootstrap a C++ project from scratch and build the target artifact. Only the essential steps are shown here; more detailed topics will be covered later.
Configure IDE/Text Editor
Read the official Microsoft documentation:
Create a Bazel Project
TODO
Migrate to Bazel Module
The directory layout looks like this:
.
├── WORKSPACE.bazel
├── BUILD.bazel
└── example
├── BUILD.bazel
├── example_lib.h
├── example_lib.cc
└── main.cc
Leave the top-level WORKSPACE.bazel
and BUILD.bazel
empty for now. Refer to the official Bazel documentation for their purposes.
// example/example_lib.h
#pragma once
namespace example {
int sum(int a, int b);
} // namespace example
// example/example_lib.cc
#include "example/example_lib.h"
namespace example {
int sum(int a, int b) { return a + b; }
} // namespace example
// example/main.cc
#include <iostream>
#include "example/example_lib.h"
int main() {
int a;
int b;
std::cin >> a >> b;
std::cout << example::sum(a, b) << std::endl;
return 0;
}
example/BUILD.bazel
:
cc_library(
name = "example_lib",
hdrs = ["example_lib.h"],
srcs = ["example_lib.cc"],
)
cc_binary(
name = "example",
srcs = ["main.cc"],
deps = [":example_lib"],
)
Build command:
bazel build //example:example
After a successful build the executable is produced at: bazel-bin/example/example
.
Other Common C/C++ Build Systems
Other frequently used build systems in the C/C++ ecosystem:
- Autotools + Makefile: the more "native" GNU toolchain combo. See Introduction to GNU Autotools.
- CMake: the de facto standard in the modern C++ world. See Effective Modern CMake.
- MSBuild (Visual Studio's build system): somewhat similar to Maven; arguably better designed, but rarely used outside Visual Studio.
Common dependency/package management approaches in C/C++:
- Rely on the OS distribution's package manager (e.g. apt/rpm/...)
- Manage yourself (e.g. copy source into a
third_party
folder/use git submodules/custom scripts to fetch & build/...) - Use dedicated package managers such as vcpkg/conan
- Build systems with partial integration capabilities (cmake/bazel/...), still requiring user effort
You must treat C++ dependency management seriously; it's more fragile than Java. A common Java issue is compiling against a newer version of a library, then deploying a lower version at runtime, causing a NoSuchMethodError
. In C++, due to the historical header/source separation model, things can go wrong more easily. Libraries with lower implementation quality are more prone to complex resource management issues and Undefined Behavior. Another recurring issue is the diamond dependency problem. In Java, if the application runs fine you might ignore it. In C++, however, ABI (Application Binary Interface) incompatibilities are frequent and will almost always cause problems.