使用该命令可以在Linux下生成(静态/动态)库so或者.a文件,Windows下就是dll与lib文件,它有两种命令格式
1.1 第一种格式 :
Normal Libraries,add_library命令的格式为
add_library( [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
[...])
生成一个名为 < name > 的library,注意以下规则:
1.2 第二种格式 :
生成一个obj文件对象,该对象库只编译源文件,但不链接。
add_library( OBJECT [...])
由add_library()或 add_executable()创建的目标可以使用$
add_library(... $ ...)
add_executable(... $ ...)
指定链接给定目标和/或其依赖项时要使用的库。命名的
target_link_libraries命令的格式
target_link_libraries( ... - ... ...)
四个文件hello.h,hello.cpp,main.cpp,CMakelist.txt,目录如下
hello.h
#include
void test(std::string str);
hello.cpp
#include "hello.h"
#include
void test(std::string str)
{
std::cout << str << std::endl;
}
main.cpp
#include "hello.h"
#include
int main(int argc, char** argv)
{
std::cout << "In main..." << std::endl;
test("hello, world!");
return 0;
}
CMakeList文件
第一种library格式
cmake_minimum_required (VERSION 3.12.1)
project (Demo)
# 生成对象库文件
add_library(hello hello.cpp)
# 添加头文件目录
target_include_directories(hello PUBLIC ${CMAKE_SOURCE_DIR}/public)
# 生成可执行文件
add_executable(Demo main.cpp)
# 链接对象库
target_link_libraries(Demo hello)
第二种library格式
cmake_minimum_required (VERSION 3.12.1)
project (Demo)
# 生成对象库文件
add_library(hello OBJECT hello.cpp)
# 添加头文件目录
target_include_directories(hello PUBLIC ${CMAKE_SOURCE_DIR}/public)
# 添加编译选项 -Wall
target_compile_options(hello PUBLIC -Wall)
# 生成可执行文件
add_executable(Demo main.cpp $)
# 添加头文件目录
target_include_directories(Demo PUBLIC ${CMAKE_SOURCE_DIR}/public)
编译,运行
另一种写法
cmake_minimum_required (VERSION 3.12.1)
project (Demo)
# 生成对象库文件,不链接
add_library(hello OBJECT hello.cpp)
# 添加头文件目录
target_include_directories(hello PUBLIC ${CMAKE_SOURCE_DIR}/public)
# 添加编译选项 -Wall
target_compile_options(hello PUBLIC -Wall)
# 生成可执行文件
add_executable(Demo main.cpp)
# 链接对象库
target_link_libraries(Demo hello)
编译,运行
大家习惯通过 $
参考:
add_library — CMake 3.22.0 Documentation
target_link_libraries — CMake 3.22.0 Documentation
cmake指令基础知识_ShawnRacine的博客-CSDN博客
cmake使用示例与整理总结_carl_wang_cn的博客-CSDN博客_cmake使用示例与整理总结