When compiling a new program, we will use third-party compiled library files or library files that we compiled ourselves. Here we will use the static and dynamic libraries that have been compiled previously.1. Using Static LibrariesThe file structure is as follows. Here we have deleted add.c and subtract.c from the src folder, keeping only main.c, while including the static library.
CMakeLists.txt
# Set the minimum required CMake version to 3.15
cmake_minimum_required(VERSION 3.15)
# Set the project name to MyProject, version number to 1.0
project(MyProject VERSION 1.0)
# Set compilation options, set C++ standard to C++17
set(CMAKE_CXX_STANDARD 17)
# Force the compiler to support the specified C++ standard (C++17 here), error if not supported.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Set header file directory
include_directories(${PROJECT_SOURCE_DIR}/include)
# Get all files ending with .c in the current directory
file(GLOB SRC_LIST ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c)
# Set the output path for the executable file
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
# Set the library file link path
link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib)
# Link library files
# libmy_static_lib.a represents the static library file
# You can also write my_static_lib directly
link_libraries(libmy_static_lib.a)
# Add executable file
add_executable(my_app ${SRC_LIST})
2. Using Dynamic Libraries
# Set the minimum required CMake version to 3.15
cmake_minimum_required(VERSION 3.15)
# Set the project name to MyProject, version number to 1.0
project(MyProject VERSION 1.0)
# Set compilation options, set C++ standard to C++17
set(CMAKE_CXX_STANDARD 17)
# Force the compiler to support the specified C++ standard (C++17 here), error if not supported.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Set header file directory
include_directories(${PROJECT_SOURCE_DIR}/include)
# Get all files ending with .c in the current directory
file(GLOB SRC_LIST ${CMAKE_CURRENT_SOURCE_DIR}/src/*.c)
# Set the output path for the executable file
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
# Set the library file link path
link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib)
# Add executable file
add_executable(my_app ${SRC_LIST})
# Link dynamic library files
# my_app is the executable file name, my_shared_lib is the dynamic library file name
# pthread is the thread library file name
# my_shared_lib is the dynamic library file name
target_link_libraries(my_app pthread my_shared_lib)
After compilation, the dynamic library must be placed in the same directory as the executable program before running the program.