Cmake 简单工程组织

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cmake 简单工程组织相关的知识,希望对你有一定的参考价值。

cmake_minimum_required(VERSION 3.0)
project(Proj)

#设置二进制可执行文件输出路径
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}/bin) #会自动创建目录

#包含依赖库的头文件
set(includelist 
dep/glfw310/include
dep/glew210/include
)
include_directories(${includelist})

#依赖库的dll,复制到bin的目录
file(GLOB_RECURSE dynamiclibs dep/*.dll)
foreach(dll ${dynamiclibs})
    file(COPY ${dll} DESTINATION ${EXECUTABLE_OUTPUT_PATH})

    #复制到编译根目录中,因为VS编译的工作目录为.vcxproj所在文件夹
    #在vs里调试运行时,会到这里来找dll
    file(COPY ${dll} DESTINATION ${CMAKE_BINARY_DIR})
endforeach()

#依赖库的lib
file(GLOB_RECURSE staticlibs dep/*.lib)
link_libraries(${staticlibs})

#程序所需资源
file(GLOB_RECURSE resourcedata res/*)
foreach(res ${resourcedata})
    file(COPY ${res} DESTINATION ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}/res)
endforeach()

#创建filter tree
macro(create_source_tree any_file)
    if(MSVC)
        set(_source_root ${CMAKE_CURRENT_SOURCE_DIR})
        foreach(_tree_file ${${any_file}})
            #变为相对路径
            string(REGEX REPLACE ${_source_root}/* "" _tree_file_path_relative ${_tree_file})   
            
            #获取文件名,不含路径
            string(REGEX REPLACE ".*/" ""  _tree_file_name ${_tree_file_path_relative})     
            
            #从相路径中去除文件名
            string(REGEX REPLACE /${_tree_file_name} ""  _tree_file_path_relative_pure ${_tree_file_path_relative})
            
            #/变为\\ 表示group
            string(REGEX REPLACE "/" "\\\\\\\\" _tree_file_path_group ${_tree_file_path_relative_pure}) 
            string(APPEND _tree_file_path_group "\\\\")
            
            #message(STATUS ${_tree_file_path_group})
            #message(STATUS ${_tree_file})
            source_group(${_tree_file_path_group} FILES ${_tree_file})
        endforeach(_tree_file)
    endif(MSVC)
endmacro(create_source_tree)

if(MSVC)
    file(GLOB_RECURSE pro_tree__tmpsource1  src/* )
    file(GLOB_RECURSE pro_tree__tmpsource2  dep/*/include/*)
    file(GLOB_RECURSE pro_tree__tmpsource3  res/*)
    set(pro_tree__all_files ${pro_tree__tmpsource1} ${pro_tree__tmpsource2} ${pro_tree__tmpsource3}) 
    create_source_tree(pro_tree__all_files)
    #为了使添加的filter出现,需要将pro_tree__all_files放到add_executable
endif(MSVC)

#程序源文件
file(GLOB_RECURSE sourcefiles  src/* )

add_executable(${CMAKE_PROJECT_NAME} ${sourcefiles} ${pro_tree__all_files})

 

以上是关于Cmake 简单工程组织的主要内容,如果未能解决你的问题,请参考以下文章

使用CMake组织C++工程3:CMake 函数和宏

cmake编译后能给vs使用吗

CMake入门实战

C++学习(四九五)一个最简单的cmake工程文件(动态链接库)

C++学习(四九五)一个最简单的cmake工程文件(动态链接库)

linux下CMake的简单介绍