乐闻世界logo
搜索文章和话题

How to create a shared library with cmake?

1个答案

1

When creating a shared library with CMake, the main steps involve creating an appropriate CMakeLists.txt file, setting up the source code, and then using CMake to generate the build system and build the library. Below is a specific example and step-by-step guide:

Step 1: Prepare the Source Code

First, prepare the source code for your library. Assume your shared library is named mylibrary and includes the following files:

  • MyLibrary.h - Library header file
  • MyLibrary.cpp - Library implementation file

File content examples:

MyLibrary.h

cpp
#ifndef MYLIBRARY_H #define MYLIBRARY_H namespace mylib { void printHello(); } #endif

MyLibrary.cpp

cpp
#include "MyLibrary.h" #include <iostream> namespace mylib { void printHello() { std::cout << "Hello from MyLibrary!" << std::endl; } }

Step 2: Write the CMakeLists.txt File

Create a file named CMakeLists.txt alongside the source files to define the build rules. For a shared library, use the add_library function and set the library type to SHARED.

cmake
cmake_minimum_required(VERSION 3.10) # Set project name and version project(MyLibrary VERSION 1.0) # Specify C++ standard set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) # Create a shared library add_library(mylibrary SHARED MyLibrary.cpp) # Specify the include directory for public header files target_include_directories(mylibrary PUBLIC "${PROJECT_SOURCE_DIR}")

Step 3: Build the Shared Library

In the source code directory, open a terminal or command prompt and execute the following commands to generate the build system and build the project:

sh
mkdir build cd build cmake .. make

This will compile the source code and generate a shared library file, such as libmylibrary.so (on Linux) or mylibrary.dll (on Windows).

Step 4: Use the Shared Library

To use this library in another project, include the library's header file and link to the generated shared library. This can be achieved using CMake's find_package or add_subdirectory (when the library and project are in the same source tree) along with target_link_libraries.

This is the fundamental workflow for creating a shared library with CMake. With this approach, you can efficiently manage and distribute your C++ library.

2024年6月29日 12:07 回复

你的答案