Swift in CMake

It is possible to use swift files in cmake projects. In my case, I added a swift based UI test to an objc project. Here is the snippet that worked:

set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES "CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED")
set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO")

set(CMAKE_Swift_LANGUAGE_VERSION 5.1)
enable_language(Swift)

unset(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES)
unset(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED)

xctest_add_bundle(myapp-test myapp
  tests/test.swift
)

initialize_ios_target(myapp-test)

When I used pthread in iOS I ran into a problem where cmake is trying to compile a small tiny program to see if the toolchain is working. Same problem here, it failed for me in the code signing step and therefor I had to turn it off for the swift compiler detection.

I had to upgrade to CMake 3.16 for this to work.

cmake Problem: pthread and iOS

A cmake build issue I came across that occurs when building with cmake and the latest version of XCode. The macro find_package(Threads) fails with

-- Looking for pthread.h - not found

Could NOT find Threads (missing: Threads_FOUND)

Digging into the log file tells it is having problems with code signing. What happens is that try_compile() compiles a very small program using pthread, and even this tiny piece needs to be code signed:

Code Signing Error: Code signing is required for product type ‘Application’ in SDK ‘iOS 13.2’

After playing around a bit, I found this workaround:

set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES "CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED")
set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO")

find_package(Threads REQUIRED)

unset(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES)
unset(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED)

Now it is able to compile the little test program and configures threads properly in cmake.