vim CMakeLists.txt
mkdir build
cd build
cmake ..
创建 CMakeLists.txt,添加内容
cmake_minimum_required(VERSION 3.26)
#工程名称
project(hello)
#宏定义
add_definitions(-D宏名称)
#头文件路径
include_directories(${PROJECT_SOURCE_DIR}/inc)
#搜索源文件.c/.cpp,并赋值到SRC
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
#编译文件输出路径
set(EXECUTABLE_OUTPUT_PATH ./bin)
#制作静态库时,静态库的输出路径
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
#生成一个可执行文件hello,添加需要编译文件,即通过aux_source_directory搜索到的文件
add_executable(hello ${SRC})
#生成一个库文件,不制作库文件时不使用
#test1生成的库文件名称,结果为libtest1
#STATIC生成静态库,libtest1.a。SHARED生成动态库libtest1.so
#${SRC}编译的文件,即通过aux_source_directory搜索到的文件
add_library(test1 STATIC ${SRC})
#静态库或者动态库路径,可指定多个
link_directories(${PROJECT_SOURCE_DIR}/lib)
#链接静态库名称test1,此处静态库为我libtest1.a,可掐头lib,去尾.a,直接写test1。可指定多个
link_libraries(test1)
一、生成可执行文件
例1
cmake_minimum_required(VERSION 3.26)
project(hello)
include_directories(${PROJECT_SOURCE_DIR}/inc)
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
set(EXECUTABLE_OUTPUT_PATH ./bin)
add_executable(hello ${SRC})
二、生成库文件
cmake_minimum_required(VERSION 3.26)
project(hello)
include_directories(${PROJECT_SOURCE_DIR}/inc)
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
#set(SRC main.c)
set(EXECUTABLE_OUTPUT_PATH ./bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
#add_executable(hello ${SRC})
add_library(test1 STATIC ${SRC})
三、链接静态库
cmake_minimum_required(VERSION 3.26)
project(hello)
include_directories(${PROJECT_SOURCE_DIR}/inc)
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
#set(SRC main.c)
set(EXECUTABLE_OUTPUT_PATH ./bin)
link_directories(${PROJECT_SOURCE_DIR}/lib)
link_libraries(test1)
add_executable(hello ${SRC})
四、链接动态库
cmake_minimum_required(VERSION 3.26)
project(hello)
include_directories(${PROJECT_SOURCE_DIR}/inc)
aux_source_directory(${PROJECT_SOURCE_DIR}/src SRC)
#set(SRC main.c)
set(EXECUTABLE_OUTPUT_PATH ./bin)
link_directories(${PROJECT_SOURCE_DIR}/lib)
#link_libraries(test1)
add_executable(hello ${SRC})
target_link_libraries(hello test1)
注意target_link_libraries(hello test1),必须写在add_executable后边