使用 CMake 为 iOS 编译

Compiling for iOS with CMake

本文关键字:编译 iOS CMake 使用      更新时间:2023-10-16

我已经使用 CMake 作为我的构建工具编译了一个C++静态库,我想将其链接到我的 iOS 应用程序。
我在 Xcode 中创建了一个简单的"Empty"应用程序,并将我的库 libengine.a 链接到它。
我尝试编译我的iOS项目,链接器给了我这个警告:

ignoring file /Users/.../build/engine/libengine.a, 
file was built for archive which is not the architecture being linked (i386):
/Users/.../build/engine/libengine.a

据我了解,我需要为 ARM 处理器编译我的库。问题是我不知道怎么做。
我认为CMake确实缺乏好的教程。
无论如何,我的CMake脚本附在下面。

任何帮助将不胜感激。
谢谢,塔尔。

这是我的主要 CMake 脚本:

cmake_minimum_required(VERSION 2.8)
project(movie-night)
if (DEFINED PLATFORM)
    include(toolchains/ios.cmake)
endif()
add_definitions(-Wall)
set(DEBUG)
if (DEFINED DEBUG)
    add_definitions(-g)
endif()
if (DEFINED RELEASE)
    add_definitions(-O3)
endif()
add_subdirectory(engine)
add_subdirectory(ui)
add_subdirectory(test)

这是我的工具链/ios.cmake 文件:

set(CMAKE_SYSTEM_NAME Darwin)
set(CMAKE_SYSTEM_PROCESSOR arm)

只需使用此工具链文件: http://code.google.com/p/ios-cmake/并将其用作

cmake -DCMAKE_TOOLCHAIN_FILE=path_to_your_toolchain_file

然后,在CMakeLists.txt

SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch armv7")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch armv7")

通过遵循 cmake-toolchains 文档,我喜欢下面:

cmake -G Xcode -B build 
    -DCMAKE_SYSTEM_NAME=iOS 
    -DCMAKE_Swift_COMPILER_FORCED=true 
    -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0

注意:定位 iOS 时,该分配CMAKE_OSX_DEPLOYMENT_TARGET=11.0不是错误。

我已经使用iOS CMake工具链的更新版本有一段时间了:https://github.com/leetal/ios-cmake

这将创建一个 Xcode 项目,如有必要,您可以将其拖到现有的 iOS 项目中。

我写了一篇博客文章,其中包含更多详细信息:https://blog.tomtasche.at/2019/05/how-to-include-cmake-project-in-xcode.html

有第二个版本的iOS.cmake位于:

https://ceres-solver.googlesource.com

注意:您可能会发现两个版本的 iOS.cmake 都只会构建项目的 x86 版本。 CMake 现在将CMAKE_OSX_SYSROOT设置为系统上可用的(最新)Mac OS X SDK。 您可以通过修改 iOS.cmake 的副本以始终设置CMAKE_OSX_SYSROOT来解决此问题。 您可以通过注释掉iOS.cmake副本的几行来执行此操作:

# -- Under CMake 3.4.2, CMAKE_OSX_SYSROOT is automatically defined to point to the latest Mac OS X SDK. --
# -- So, the iOS SDK is never found.  Grab the correct CMAKE_OS_SYSROOT and ignore any prior setting.   --
# If user did not specify the SDK root to use, then query xcodebuild for it.
# if (NOT CMAKE_OSX_SYSROOT)
  execute_process(COMMAND xcodebuild -version -sdk ${XCODE_IOS_PLATFORM} Path
    OUTPUT_VARIABLE CMAKE_OSX_SYSROOT
    ERROR_QUIET
    OUTPUT_STRIP_TRAILING_WHITESPACE)
  message (STATUS "Using SDK: ${CMAKE_OSX_SYSROOT} for platform: ${IOS_PLATFORM}")
  message (STATUS "be sure the previous line points to the correct SDK")
# endif ( )