Skip to content

Compile C++ Code

This note is about how to compile the C++ code into executables. As far as I remember, I started compiling C++ code with Bazel. Yes, I didn't start compiling C++ code with gcc or g++, which actually took me a while to understand how to use it. I still don't know how to use gcc or g++ very well. That's why I have this document

Compile Simple C++ Code

Both gcc and g++ comes with my Ubuntu Linux Distribution. At first, I don't really know what is the difference between these two, until I got a compilation error with my C++ code, which I named it something like foo.cc. After consulting ChatGPT, I realize I probably should use g++ to compile my C++ code by default, especially I do intend to write C++ instead of C. One major difference is g++ automatically link C++ standard libraries, whereas gcc may link the C standard libraries.

For a simple c++ binary, we can just do

$ g++ -o uniq uniq.cc

The -o option is a common option for Unix/Linux tools, telling the tool to name the output, in this case, the executable, as uniq. uniq.cc is the source file, and g++ will magically link all C++ standard libraries to the object file created by uniq.cc before assemble the final executable.

If -o uniq is NOT provided, g++ will create a file named a.out, which is the same thing as the previous uniq executable, just in a different name.

$ g++ -o uniq uniq.cc
$ g++ uniq.cc
$ diff uniq a.out  # no output
$ echo $#  # further check the return of last command is 0, which means no diff.
0 

Todo

check why the default name is a.out and what does it mean.

use Make to organize build system

use Bazel as the build system.

the basis of building a C++ library or a binary is to use cc_binary and cc_library macros in a BUILD file. Note that, BUILD files have to stay in a workspace, which is defined by having a WORKSPACE file at the "root" level of a directory. Assume we have a directory structure, and the content in the BUILD file

/root
|--- WORKSPACE
|--- /app
|    |--- BUILD
|    |--- uniq.cc
BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary")

cc_binary(
    name = "uniq",
    srcs = ["uniq.cc"],
)

then you can just run to build a binary uniq. Of course, there is a lot of configurations in Bazel that will get into the build. Those are topics to be added.

$ bazel build //app:uniq