CMake教程(二):构建和链接库
本文将以介绍CMake如何构建和链接库。
首先,我们需要构建一个message库,其包含一个Message类,该类封装了一个字符串。Message类由两个文件组成:Message.cpp文件和它的头文件Message.hpp。Message.hpp文件如下:
#pragma once
#include <iosfwd>
#include <string>
class Message {
public:
Message(const std::string &m) : message_(m) {}
friend std::ostream &operator<<(std::ostream &os, Message &obj) {
return obj.printObject(os);
}
private:
std::string message_;
std::ostream &printObject(std::ostream &os);
};
Message.cpp文件如下:
#include "Message.hpp"
#include <iostream>
#include <string>
std::ostream &Message::printObject(std::ostream &os) {
os << "This is my very nice message: " << std::endl;
os << message_;
return os;
}
在hello-world.cpp文件中用Message类和相关接口:
#include "Message.hpp"
#include <cstdlib>
#include <iostream>
int main() {
Message say_hello("Hello, CMake World!");
std::cout << say_hello << std::endl;
Message say_goodbye("Goodbye, CMake World");
std::cout << say_goodbye << std::endl;
return EXIT_SUCCESS;
}
该工程编译中先生成Message库,再编译hello-world程序。如下的CMakeLists.txt文件可以实现上述功能:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-03 LANGUAGES CXX)
set(IS_STATIC_LIB ON CACHE STRING "static lib")
# option(USE_LIBRARY "Compile sources into a library" OFF)
if (IS_STATIC_LIB)
message(STATUS "Static lib")
add_library(message
STATIC
Message.hpp
Message.cpp
)
else()
add_library(message
SHARED
Message.hpp
Message.cpp
)
endif()
add_executable(hello-world hello-world.cpp)
target_link_libraries(hello-world message)
set/option中设置了参数IS_STATIC_LIB来控制生成静态库或者动态库。add_library中设置需要编译的库名称,以及相关的依赖文件。
整个工程的目录结构如下:
.
├── CMakeLists.txt
├── hello-world.cpp
├── Message.cpp
└── Message.hpp
0 directories, 4 files
运行如下命令
mkdir build
cd build
cmake .. -D IS_STATIC_LIB=OFF
cmake --build .
后,在build目录下生成了动态库libmessage.so和可执行文件hello-world。