Usage of Libraries with CMake

Command in CMake

add_library
add_library(<name> [STATIC | SHARED | MODULE]
            [EXCLUDE_FROM_ALL]
            [<source>...])

add_library documentation

Example CMakeLists.txt for library

CMakeLists.txt
cmake_minimum_required(VERSION 3.0)

project(mymath)

add_library(mymath adder.cpp)

Working Example

Working Example
gt.sandbox.checkout.commit.cleanly 9671ea2 \
&& cd "$GT_SANDBOX_REPO/cpp/LibProducer" \
&& cmake -S . -B ./build \
&& cd build \
&& make \
&& cd "$GT_SANDBOX_REPO/cpp/LibConsumer" \
&& cmake -S . -B ./build \
&& cd build \
&& make \
&& echo "Running ./LibConsumer" \
&& ./LibConsumer
Output of building library
...
[ 50%] Building CXX object CMakeFiles/mymath.dir/adder.cpp.o
[100%] Linking CXX static library libmymath.a
[100%] Built target mymath

note lib prefix is added and .a suffix is added.

The default output of add_library is static library of .a.

.a static library will contain the definitions. But will still need the declaration (the header file).


Backlinks