Creating a static library is a common requirement when building projects with CMake. A static library is a collection of compiled code that can be linked to the program during compilation, rather than being dynamically loaded at runtime. Below, I will provide a detailed explanation of how to create a static library in CMake, along with a practical example.
Step 1: Prepare Source Code
First, prepare the source code intended for compilation into a static library. Assume we have a simple project containing two files: library.cpp and library.h.
library.h
cpp#ifndef LIBRARY_H #define LIBRARY_H void print_hello(); #endif
library.cpp
cpp#include "library.h" #include <iostream> void print_hello() { std::cout << "Hello, Static Library!" << std::endl; }
Step 2: Write the CMakeLists.txt File
Next, you need to write a CMakeLists.txt file to instruct CMake on how to compile these source files and create a static library.
CMakeLists.txt
cmakecmake_minimum_required(VERSION 3.10) # Specify the minimum CMake version requirement project(MyStaticLibrary) # Define the project name add_library(mylib STATIC # Create the static library `mylib` library.cpp library.h )
Here, the add_library command is used to create a new library. mylib is the name of the library, STATIC specifies that we are creating a static library, followed by the source files to be compiled into the library.
Step 3: Compile the Project
To compile this library, execute the following commands:
- Create a build directory and enter it:
bashmkdir build cd build
- Run CMake to configure the project and generate the build system:
bashcmake ..
- Compile the code:
bashcmake --build .
After executing these commands, you will find the compiled static library file (e.g., libmylib.a, which may vary by platform) in the build directory.
Summary
Through the above steps, we successfully created a static library using CMake. This method is widely used in practical development as it helps modularize code, improve code reusability, and simplify the management of large projects.