一、背景
前面介绍了add_library的两种格式,今天分享一个实例:
Cmake分别生成静态链接库,OBJ链接库,并使用$<TARGET_OBJECTS:name>引用obj文件
二、实例
文件目录如下
CMakeList.txt文件
# set minimum cmake version
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
# project name and language
project(recipe-03 LANGUAGES CXX)
# generate an object library from sources
add_library(message-objs
OBJECT
Message.hpp
Message.cpp
)
# 开启(PIC) 编译动态库
set_target_properties(message-objs
PROPERTIES
POSITION_INDEPENDENT_CODE True
)
add_library(message-shared
SHARED
$<TARGET_OBJECTS:message-objs>
)
set_target_properties(message-shared
PROPERTIES
OUTPUT_NAME "message"
)
add_library(message-static
STATIC
$<TARGET_OBJECTS:message-objs>
)
set_target_properties(message-static
PROPERTIES
OUTPUT_NAME "message"
)
add_executable(hello-world hello-world.cpp)
target_link_libraries(hello-world message-static)
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-word.cpp
#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;
}
新建bulid目录,windows下编译:cmake -G"Unix Makefiles" ../,得到三个 libmessage的链接库。(Linux下编译一直报错,把hello-word.cpp换个名字,比如main.cpp,就好了)
运行
参考:
add_library — CMake 3.22.4 Documentation