Introduction to CMake (3) compilation and use of dynamic and static libraries

Keywords: cmake

1, Compilation of dynamic library and static library

First create a new CMakeLists.txt

Knock in

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
ADD_SUBDIRECTORY(src/shared)
ADD_SUBDIRECTORY(src/static)

Then create the src folder in the project directory, and then create the shared and static folders in src

Dynamic library

Create include, src, CMakeLists.txt under src/shared
Create the header file shared.h under include

#include <iostream>

void sayShared();

The implementation of share. H under src

#include <shared.h>

void sayShared(){
    std::cout << "Shared!" << std::endl;
}

Then type in under CMakeLists.txt

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
SET(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/lib")
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src/shared/src SHARED_SRC)
INCLUDE_DIRECTORIES("${PROJECT_SOURCE_DIR}/src/shared/include")
ADD_LIBRARY(shared SHARED ${SHARED_SRC})

Static library

Create include, src, CMakeLists.txt under src/static
Create header file static.h under include

#include <iostream>

void sayStatic();

Implementation of static.h under src static.cpp

#include <static.h>

void sayStatic(){
    std::cout << "Static!" << std::endl;
}

Then type in under CMakeLists.txt

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
SET(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/lib")
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/src/static/src STATIC_SRC)
INCLUDE_DIRECTORIES("${PROJECT_SOURCE_DIR}/src/static/include")
ADD_LIBRARY(static STATIC ${STATIC_SRC})

New script build.sh

#!/bin/bash
dir="./build"
[ -d "$dir" ] && rm -rf "$dir"
mkdir "$dir"
cd "$dir"
cmake ..
make

The preparatory work is finished. The contents are as follows

Then run

./build.sh

You can compile dynamic and static libraries

Compiled library files will appear under build/lib

2, Use of dynamic and static libraries

Just make a change to the above project
Modify CMakeLists.txt in the root directory and add the directory to be used

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
ADD_SUBDIRECTORY(src/shared)
ADD_SUBDIRECTORY(src/static)
ADD_SUBDIRECTORY(example)

Create a new example. Create CMakeLists.txt and main.cpp under example
CMakeLists.txt typing in

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
SET(EXECUTABLE_OUTPUT_PATH "${PROJECT_BINARY_DIR}/bin")
AUX_SOURCE_DIRECTORY(${PROJECT_SOURCE_DIR}/example MAIN_SRC)
INCLUDE_DIRECTORIES("${PROJECT_SOURCE_DIR}/src/shared/include")
INCLUDE_DIRECTORIES("${PROJECT_SOURCE_DIR}/src/static/include")
LINK_DIRECTORIES("${PROJECT_BINARY_DIR}/lib")
ADD_EXECUTABLE(hello ${MAIN_SRC})
TARGET_LINK_LIBRARIES(hello libshared.so)
TARGET_LINK_LIBRARIES(hello libstatic.a)

main.cpp in

#include <shared.h>
#include <static.h>

int main()
{
    sayShared();
    sayStatic();
    return 0;
}

The file directory is shown in the figure below

Then run the build script

./build.sh

Execute the hello under bin and it will be ok

Posted by Dysan on Wed, 13 May 2020 09:03:48 -0700