Oct 10, 2023

CMake Study

Technical notes for CMake.

Create a New Build

Adding a Library

Create a new directory, my_library (or any name). I’ll create an example library called adder. I’ll also create two files in this directory: adder.h and adder.cpp.


Note that PRIVATE it represents the visibility of the library. PRIVATE means that the library is only used by the target. Other options are PUBLIC and INTERFACE. PUBLIC means that the library is used by the target and any targets that link to this target. INTERFACE means that the library is used by any targets that link to this target but not the target itself.

In our case, the target is MyApp, but bigger projects may have multiple targets, so the visibility options are a powerful way to control dependencies.

With this setup, we can go to the build directory and build the project:

Linking a Compiled Library

The above approach links a library when you can access the source code and want to compile the library yourself. However, sometimes, you only have access to the compiled library file. Note that compiled libraries still need a header file to use them. Compiled libraries usually have these file extensions:

STATIC: .a, .lib

SHARED: .so, .dll, .dylib

Note that .lib and .dll are used on Windows, .a and .so are used on Linux, and .a and .dylib are used on macOS.

Static means that a library will be compiled into your executable. This means that the library code is “embedded” into your final application. If multiple executable files use it, then the library code will be duplicated in each of them.

A shared library is not embedded into your application. Instead, it is loaded at runtime. This means that if multiple executable files use it, then the library code will be loaded only once in memory. However, this also means that you must distribute the library file with your application and ensure the library is available on the user’s machine. Static libraries are usually easier to use, but shared libraries are more efficient. Here’s how to link a pre-compiled library:

In this example, I’ll use two files in the my_library directory:

I’m including the header file in the my_library directory, then I’m calling target_link_libraries the same way as before, but this time, it is linked to the a file. Although I’m linking a static library, the approach is the same for the other types as well.

Note that CMAKE_SOURCE_DIR is part of the CMake API, and it represents the root directory where CMakeLists.txt is located.

Build Tools

C/C++

CMake

Back to Notes