一、准备代码
1. main.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;
}
2. 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) ;
} ;
3. 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;
}
二、CMakeLists.txt
1. 静态库CMakeLists.txt
cmake_minimum_required ( VERSION 3.10 FATAL_ERROR)
project ( sample_002 LANGUAGES CXX)
# 第二个参数 STATIC 表示把 Message. cpp和Message. hpp编译成静态库
add_library ( message
STATIC
Message. hpp
Message. cpp
)
add_executable ( hello- world main. cpp)
target_link_libraries ( hello- world message)
2. 动态库CMakeLists.txt
cmake_minimum_required ( VERSION 3.10 FATAL_ERROR)
project ( sample_002 LANGUAGES CXX)
# 第二个参数 SHARED 表示把 Message. cpp和Message. hpp编译成动态库
add_library ( message
SHARED
Message. hpp
Message. cpp
)
add_executable ( hello- world main. cpp)
target_link_libraries ( hello- world message)
3. BUILD_SHARED_LIBS
cmake_minimum_required ( VERSION 3.10 FATAL_ERROR)
project ( sample_002 LANGUAGES CXX)
# 是否编译动态库,与add_library的第二个参数有关,添加此变量后,add_library第二个参数可省略
# 当设置为 OFF 时, 编译成静态库
# 当设置为 ON 时,编译成动态库
set ( BUILD_SHARED_LIBS OFF)
add_library ( message
Message. hpp
Message. cpp
)
add_executable ( hello- world main. cpp)
target_link_libraries ( hello- world message)
三、编译运行
mkdir -p build
cd build
cmake ..
cmake --build .
./hello-world
四、总结
add_library(message STATIC Message.hpp Message.cpp)
:生成静态库libmessage.a
;add_library(message SHARED Message.hpp Message.cpp)
:生成动态库libmessage.so
;静态库和动态库主要区别在add_library
的第二个参数(此参数缺省等同于STATIC
):
参数值 说明 STATIC 用于创建静态库,即编译文件的打包存档,以便在链接其他目标时使用 HARED 用于创建动态库,即可以动态链接,并在运行时加载的库 OBJECT 可将给定add_library的列表中的源码编译到目标文件,不将它们归档到静态库中,也不能将它们链接到共享对象中 MODULE 又为DSO组。与SHARED库不同,它们不链接到项目中的任何目标,不过可以进行动态加载。该参数可以用于构建运行时插件
target_link_libraries(hello-world message)
:将libmessage
库链接到可执行文件hello-world
中;target_link_libraries
命令还确保hello-world
可执行文件可以正确地依赖于消息库。因此,在消息库libmessage
链接到hello-world
可执行文件之前,需要完成消息库libmessage
的构建