CMake的常规使用+ios静态库的编译方法



  • CMake是一个很便捷的跨平台编译工具,只要把目录结构排版好,写一个CMakeLists.txt告诉CMake怎么去生成makefile就ok了。


    基本用法

    # 目录结构
    -/ *(根目录)
    |-CMakeLists.txt
    |-main.cpp
    |-ios.toolchain.cmake *(可选项,用来编译ios项目用,下面会提供下载地址)
    |-build *(用来存放编译后可执行文件的目录)
    |-library *(用来存放编译后生成静态库的目录)
    |-utils *(utils静态库源码目录)
        |-CMakeLists.txt
        |-utils.cpp
        |-mem.cpp
        |-utils.h
        |-mem.cpp
    

    根目录中的CMakeLists.txt

    # 项目名称
    project(ANLib)
    # 设置CMake最小版本
    cmake_minimum_required(VERSION 2.8)
    set(CMAKE_MACOSX_RPATH 0)
    # 代码路径
    aux_source_directory(. test_src)
    #设置编译器
    set(CMAKE_CXX_COMPILER "g++")
    #设置构建类型,及相应的编译选项
    set(CMAKE_BUILD_TYPE "Release")
    set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb -m64")
    set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall -m64")
    
    #设置执行文件输出目录
    set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build)
    #设置库输出路径
    set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/library)
    
    #设置utils库源码路径
    set(utils_dir ./utils)
    add_subdirectory(${utils_dir})
    include_directories(${utils_dir})
    
    link_directories(${PROJECT_SOURCE_DIR}/library)
    
    # 生成可执行的文件
    add_executable(test ${test_src})
    target_link_libraries(test utils)
    
    

    utils目录中的CMakeLists.txt

    set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/library)
    aux_source_directory(. dir_srcs)
    add_library(utils STATIC ${dir_srcs})
    target_link_libraries(utils)
    

    开始使用Cmake

    切换到根目录中,编译项目:

    cmake .
    make
    

    在mac中使用cmake编译ios的静态库:(需要mac os系统)

    clone以下项目,让后将’ios.toolchain.cmake’放到根目录中(以下链接选一个下载)
    https://code.google.com/archive/p/ios-cmake/downloads
    https://github.com/leetal/ios-cmake

    切换到根目录中,编译项目:

    cmake . -DCMAKE_TOOLCHAIN_FILE=./ios.toolchain.cmake -DIOS_PLATFORM=SIMULATOR64
    make
    

    相关选项说明:

    Set -DIOS_PLATFORM to "SIMULATOR" to build for iOS simulator 32 bit (i386) DEPRECATED
    Set -DIOS_PLATFORM to "SIMULATOR64" (example above) to build for iOS simulator 64 bit (x86_64)
    Set -DIOS_PLATFORM to "OS" to build for Device (armv7, armv7s, arm64, arm64e)
    Set -DIOS_PLATFORM to "OS64" to build for Device (arm64, arm64e)
    Set -DIOS_PLATFORM to "TVOS" to build for tvOS (arm64)
    Set -DIOS_PLATFORM to "SIMULATOR_TVOS" to build for tvOS Simulator (x86_64)
    Set -DIOS_PLATFORM to "WATCHOS" to build for watchOS (armv7k, arm64_32)
    Set -DIOS_PLATFORM to "SIMULATOR_WATCHOS" to build for watchOS Simulator (x86_64)
    

Log in to reply