Cmake是C++编译比较常用的工具,在对C++ main.cpp进行编译时,如若调用子cpp文件,需进行library链接,调用第三方库时,需要在Cmakelists文件中手动设置并编译链接后,main.cpp才可调用。
cmake_minimum_required(VERSION 3.5)
project(YOUR_PROJECT_NAME)
############################################################
# Create a library
############################################################
# add OpenCV/OpenGL/GLEW/glfw3
find_package(OpenCV REQUIRED)
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(glfw3 REQUIRED)
# set path of glfw3
set(glfw3_LIBS /usr/lib/x86_64-linux-gnu/libglfw.so)
# Add OpenCV headers location to your include paths
include_directories(${OpenCV_INCLUDE_DIRS}
${OPENGL_INCLUDE_DIR} # 第一句已经添加了足够的头文件路径,不需要再加
${GLEW_INCLUDE_DIRS}
${glfw3_INCLUDE_DIRS}
)
#Generate the static library from the library sources
add_library(YOUR_PROJECT_NAME STATIC
src/SUBFILE0.cpp
src/SUBFILE1.cpp
src/SUBFILE2.cpp
)
target_include_directories(YOUR_PROJECT_NAME
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
############################################################
# Create an executable
############################################################
# Add an executable with the above sources
add_executable(YOUR_PROJECT_NAME
src/main.cpp
)
# link the new hello_library target with the hello_binary target
target_link_libraries(YOUR_PROJECT_NAME
PRIVATE
YOUR_PROJECT_NAME
${OpenCV_LIBS}
${OPENGL_LIBRARIES}
${GLEW_LIBRARIES}
${glfw3_LIBS}
)
find_package()为寻找第三方库的指令,一般来说大部分第三方库都会针对cmake给出对应的config.cmake文件,当cmake找到该库时,find_package()会返回几个变量,以OpenCV为例,OpenCV_INCLUDE_DIRS表示库所在的根目录,include_directories()表示将OpenCV根目录添加到搜索路径中,至此在cpp文件调用OpenCV库时,能够找到相应的函数。
add_library()将子cpp文件与main.cpp设置静态链接,使main.cpp能够调用子cpp文件中定义的函数。
target_link_libraries()将project与第三方动态库libraries链接到一起。
但是有的库config.cmake文件写的不够完善,或是说返回的变量我们很难知道具体名称是什么,比如glfw3库,这时就可以采用手动查找路径并变量赋值的方式来链接动态库。
# set path of glfw3
set(glfw3_LIBS /usr/lib/x86_64-linux-gnu/libglfw.so)
.so文件一般处于上述位置,找不到的话也可以仿照OpenCV的位置顺藤摸瓜,一般都在一个文件夹下。