All You Need for CMake系列04——Shared Library

准备代码

代码结构如下:

.
├── CMakeLists.txt
├── include
│   └── shared
│       └── Hello.h
└── src
    ├── Hello.cpp
    └── main.cpp

这是一个经典结构,moveit里面单独的包都是用这种方式写的。

Hello.h里内容如下:

#ifndef __HELLO_H__
#define __HELLO_H__

class Hello
{
public:
    void print();
};

#endif

Hello.cpp里内容如下:

#include <iostream>

#include "shared/Hello.h"

void Hello::print()
{
    std::cout << "Hello Shared Library!" << std::endl;
}

main.cpp

#include "shared/Hello.h"

int main(int argc, char *argv[])
{
    Hello hi;
    hi.print();
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(hello_library)

############################################################
# Create a library
############################################################

#Generate the shared library from the library sources
add_library(hello_library SHARED 
    src/Hello.cpp
)
add_library(hello::library ALIAS hello_library)

target_include_directories(hello_library
    PUBLIC 
        ${PROJECT_SOURCE_DIR}/include
)

############################################################
# Create an executable
############################################################

# Add an executable with the above sources
add_executable(hello_binary
    src/main.cpp
)

# link the new hello_library target with the hello_binary target
target_link_libraries( hello_binary
    PRIVATE 
        hello::library
)

要点

  1. 在本教程中演示了如何在CMakeLists.txt中添加对动态lib的支持,在创建library的时候,只用把关键词STATIC替换成SHARED。那句add_library(hello::library ALIAS hello_library)只是一个添加别名的作用,是说让它可以用这个名字被link上(下面的link就是这么操作的)
  2. 当然如果不用别名的话,和STATIC的lib比起来就没有多少区别了
  3. 动态lib的输出是.so文件

编译流程

mkdir build
cd build
cmake ..
make