├── .github ├── actions │ └── cmake-action │ │ └── action.yml └── workflows │ └── pull_request.yml ├── .mailmap ├── 1_single_executable ├── CMakeLists.txt ├── Readme.md └── hello.swift ├── 2_executable_library ├── CMakeLists.txt ├── Readme.md ├── lib │ ├── CMakeLists.txt │ └── factorial.swift └── src │ ├── CMakeLists.txt │ └── main.swift ├── 3_bidirectional_cxx_interop ├── CMakeLists.txt ├── Readme.md ├── cmake │ └── modules │ │ ├── AddSwift.cmake │ │ └── InitializeSwift.cmake ├── include │ └── fibonacci │ │ ├── fibonacci.h │ │ └── module.modulemap ├── lib │ └── fibonacci │ │ ├── CMakeLists.txt │ │ ├── fibonacci.cpp │ │ └── fibonacci.swift └── src │ ├── CMakeLists.txt │ ├── fibonacci.cpp │ └── fibonacci.swift ├── 4_swift_macros ├── CMakeLists.txt ├── StringifyMacro │ ├── CMakeLists.txt │ └── macro.swift ├── main.swift └── readme.md ├── CMakeLists.txt ├── CONTRIBUTING.md ├── LICENSE.txt └── README.md /.github/actions/cmake-action/action.yml: -------------------------------------------------------------------------------- 1 | name: 'Install CMake' 2 | description: 'Download and configure CMake' 3 | inputs: 4 | url: 5 | description: "URL of CMake bundle to download" 6 | hash: 7 | description: "Expected bundle hash" 8 | install_dir: 9 | description: "Location where to install the CMake bundle" 10 | default: /tmp/cmake 11 | 12 | outputs: 13 | cmake: 14 | description: "Path to the installed CMake executable." 15 | value: ${{ steps.unpack-cmake.outputs.cmake-path }} 16 | ctest: 17 | description: "Path to the installed CMake ctest executable." 18 | value: ${{ steps.unpack-cmake.outputs.ctest-path }} 19 | runs: 20 | using: "composite" 21 | steps: 22 | - name: Download CMake 23 | shell: bash 24 | run: | 25 | curl -Llo /tmp/cmake.tar.gz "${{ inputs.url }}" 26 | - name: Verify CMake 27 | shell: bash 28 | run: 29 | echo "${{ inputs.hash }} /tmp/cmake.tar.gz" | shasum -a 256 -c- 30 | - name: Unpack CMake 31 | shell: bash 32 | id: unpack-cmake 33 | run: | 34 | mkdir "${{ inputs.install_dir }}" 35 | tar xf /tmp/cmake.tar.gz --strip-components=1 -C "${{ inputs.install_dir }}" 36 | echo "cmake-path=${{ inputs.install_dir }}/bin/cmake" >> "$GITHUB_OUTPUT" 37 | echo "ctest-path=${{ inputs.install_dir }}/bin/ctest" >> "$GITHUB_OUTPUT" 38 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request 2 | on: 3 | pull_request: 4 | branches: 5 | - main 6 | types: 7 | - opened 8 | - reopened 9 | - synchronize 10 | 11 | jobs: 12 | smoke_test: 13 | name: Smoke Test (CMake v${{ matrix.cmake.version }}) 14 | runs-on: ubuntu-latest 15 | container: swift:6.1-bookworm 16 | strategy: 17 | matrix: 18 | cmake: 19 | - version: 3.22.6 20 | hash: 09e1b34026c406c5bf4d1b053eadb3a8519cb360e37547ebf4b70ab766d94fbc 21 | - version: 3.26.6 22 | hash: 2dd48ccd3e3d872ee4cc916f3f4e24812612421007e895f82bf9fc7e49831d62 23 | - version: 3.30.8 24 | hash: adc81f2944e6f86b44e86acea3abea1651ed7890206933484b8b74ac1280314f 25 | - version: 4.0.1 26 | hash: d66c11c010588c8256ee20a26b45977cd5b2f4aee2b742d4b8a353769940d147 27 | steps: 28 | - name: Clone Repo 29 | uses: actions/checkout@v4 30 | with: 31 | path: ./swift-cmake-examples 32 | - name: Install Dependencies 33 | shell: bash 34 | run: apt update && apt install -y curl ninja-build 35 | - name: Setup CMake 36 | id: install-cmake 37 | uses: ./swift-cmake-examples/.github/actions/cmake-action 38 | with: 39 | url: "https://github.com/Kitware/CMake/releases/download/v${{matrix.cmake.version}}/cmake-${{matrix.cmake.version}}-linux-x86_64.tar.gz" 40 | hash: ${{ matrix.cmake.hash }} 41 | - name: Run Tests 42 | shell: bash 43 | run: | 44 | "${{ steps.install-cmake.outputs.cmake }}" -G Ninja -B test -S swift-cmake-examples -DCMAKE_BUILD_TYPE=Release 45 | "${{ steps.install-cmake.outputs.ctest }}" --output-on-failure --test-timeout 150 --test-dir test -j 46 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Evan Wilde 2 | -------------------------------------------------------------------------------- /1_single_executable/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | cmake_minimum_required(VERSION 3.22...3.29) 9 | 10 | project(hello LANGUAGES Swift) 11 | 12 | add_executable(hello hello.swift) 13 | -------------------------------------------------------------------------------- /1_single_executable/Readme.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | 3 | This is the simplest usage of Swift and CMake, building a single swift 4 | executable. 5 | 6 | ## Build Instructions 7 | 8 | ### macOS and Linux: 9 | 10 | ```sh 11 | $ mkdir build && cd build 12 | $ cmake -G 'Ninja' ../ 13 | $ ninja hello 14 | $ ./hello 15 | Hello, world! 16 | ``` 17 | 18 | ## Build Results 19 | 20 | Building this project results in a single executable, `hello` in the build 21 | directory. 22 | -------------------------------------------------------------------------------- /1_single_executable/hello.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | print("Hello, world!") 13 | -------------------------------------------------------------------------------- /2_executable_library/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | cmake_minimum_required(VERSION 3.22...3.29) 9 | project(Project2 LANGUAGES Swift) 10 | 11 | add_subdirectory("lib/") 12 | add_subdirectory("src/") 13 | -------------------------------------------------------------------------------- /2_executable_library/Readme.md: -------------------------------------------------------------------------------- 1 | # Factorials 2 | 3 | This program demonstrates using CMake to build a Swift executable that uses a 4 | Swift library. 5 | 6 | ## Build Instructions 7 | 8 | ### macOS and Linux: 9 | 10 | ```sh 11 | $ mkdir build && cd build 12 | $ cmake -G 'Ninja' ../ 13 | $ ninja factorials 14 | $ ./src/factorials 15 | 16 | factorial(0) = 1 17 | factorial(1) = 1 18 | factorial(2) = 2 19 | factorial(3) = 6 20 | factorial(4) = 24 21 | factorial(5) = 120 22 | factorial(6) = 720 23 | factorial(7) = 5040 24 | factorial(8) = 40320 25 | factorial(9) = 362880 26 | factorial(10) = 3628800 27 | ``` 28 | 29 | ## Build Results 30 | 31 | This project results in two primary build products, the `factorial` library, and 32 | the `factorials` executable The library and the corresponding swiftmodule live 33 | under the `lib/` directory, while the executable lives under the `src/` 34 | directory. 35 | -------------------------------------------------------------------------------- /2_executable_library/lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | add_library(factorial factorial.swift) 9 | -------------------------------------------------------------------------------- /2_executable_library/lib/factorial.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | public func factorial(x: Int) -> Int { 13 | if x <= 0 { 14 | return 1 15 | } 16 | return x * factorial(x: x - 1) 17 | } 18 | -------------------------------------------------------------------------------- /2_executable_library/src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | add_executable(factorials main.swift) 9 | target_link_libraries(factorials PRIVATE factorial) 10 | -------------------------------------------------------------------------------- /2_executable_library/src/main.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | import factorial 13 | 14 | for x in 0...10 { 15 | print("factorial(\(x)) = \(factorial(x: x))") 16 | } 17 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | cmake_minimum_required(VERSION 3.26...3.29) 9 | 10 | # Project PingPong: Bouncing control flow between Swift and C++ like a ping pong 11 | # ball. 12 | project(PingPong LANGUAGES CXX Swift) 13 | 14 | # Verify that we have a new enough compiler 15 | if("${CMAKE_Swift_COMPILER_VERSION}" VERSION_LESS 5.9) 16 | message(FATAL_ERROR "Bidirectional C++ Interop requires Swift 5.9 or greater. Have ${CMAKE_Swift_COMPILER_VERSION}") 17 | endif() 18 | 19 | if(NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND 20 | NOT "${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") 21 | message(FATAL_ERROR "Project requires building with Clang. 22 | Have ${CMAKE_CXX_COMPILER_ID}") 23 | endif() 24 | 25 | list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") 26 | 27 | # Set up swiftrt.o and runtime library search paths 28 | include(InitializeSwift) 29 | # cmake/modules/AddSwift.cmake provides the function for creating the Swift to 30 | # C++ bridging header 31 | include(AddSwift) 32 | 33 | set(PINGPONG_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include") 34 | set(PINGPONG_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/lib") 35 | set(PINGPONG_SRC_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src") 36 | set(PINGPONG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}") 37 | 38 | set(CMAKE_OSX_DEPLOYMENT_TARGET 13.0) 39 | set(CMAKE_CXX_STANDARD 17) 40 | 41 | include_directories(${PINGPONG_INCLUDE_DIR}) 42 | 43 | add_subdirectory("${PINGPONG_LIB_DIR}/fibonacci") 44 | add_subdirectory("src/") 45 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/Readme.md: -------------------------------------------------------------------------------- 1 | # Ping Pong 2 | 3 | This project demonstrates using Swift/C++ interop, creating two executables and 4 | two libraries. One executable is written in C++, calling into a Swift library, 5 | which calls into a C++ library. The other executable is written in Swift, 6 | calling into a C++ library, which calls into a Swift library, bouncing control 7 | flow between the two languages to compute fibonacci numbers. 8 | 9 | ## Requirements 10 | - Swift 5.9 or later 11 | - Clang 11 or Apple Clang shipped in Xcode 12 or newer 12 | - CMake 3.26 or later 13 | - Ninja 14 | 15 | ## Build 16 | 17 | ```sh 18 | $ mkdir build 19 | $ cd build 20 | $ cmake -G 'Ninja' ../ 21 | $ ninja 22 | ``` 23 | 24 | ## Run 25 | 26 | Start in the build directory you created above. There are two executables under 27 | `src/`. `src/fibonacci_cpp` is a program written in C++ that calls into a Swift 28 | library, which calls back into C++. `src/fibonacci_swift` is a program written 29 | in Swift that calls into a C++ library, which calls back into Swift. Both 30 | compute the n'th fibonacci number, where `n` is 5. 31 | 32 | Each step of computing the numbers prints whether it's running in Swift or C++, 33 | and the value `x` at that step. 34 | 35 | ```sh 36 | $ ./src/fibonacci_cpp 37 | x [swift]: 5 38 | x [cpp]: 4 39 | x [swift]: 3 40 | x [cpp]: 2 41 | x [swift]: 1 42 | x [swift]: 0 43 | x [cpp]: 1 44 | x [swift]: 2 45 | x [cpp]: 1 46 | x [cpp]: 0 47 | x [cpp]: 3 48 | x [swift]: 2 49 | x [cpp]: 1 50 | x [cpp]: 0 51 | x [swift]: 1 52 | 8 53 | 54 | $ ./src/fibonacci_swift 55 | x [cpp]: 5 56 | x [swift]: 4 57 | x [cpp]: 3 58 | x [swift]: 2 59 | x [cpp]: 1 60 | x [cpp]: 0 61 | x [swift]: 1 62 | x [cpp]: 2 63 | x [swift]: 1 64 | x [swift]: 0 65 | x [swift]: 3 66 | x [cpp]: 2 67 | x [swift]: 1 68 | x [swift]: 0 69 | x [cpp]: 1 70 | 8 71 | ``` 72 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/cmake/modules/AddSwift.cmake: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | 9 | # Generate the bridging header from Swift to C++ 10 | # 11 | # target: the name of the target to generate headers for. 12 | # This target must build swift source files. 13 | # header: the name of the header file to generate. 14 | # 15 | # NOTE: This logic will eventually be unstreamed into CMake. 16 | function(_swift_generate_cxx_header target header) 17 | if(NOT TARGET ${target}) 18 | message(FATAL_ERROR "Target ${target} not defined.") 19 | endif() 20 | 21 | if(NOT DEFINED CMAKE_Swift_COMPILER) 22 | message(WARNING "Swift not enabled in project. Cannot generate headers for Swift files.") 23 | return() 24 | endif() 25 | 26 | cmake_parse_arguments(ARG "" "" "SEARCH_PATHS;MODULE_NAME" ${ARGN}) 27 | 28 | if(NOT ARG_MODULE_NAME) 29 | set(target_module_name $) 30 | set(ARG_MODULE_NAME $,${target_module_name},${target}>) 31 | endif() 32 | 33 | if(ARG_SEARCH_PATHS) 34 | list(TRANSFORM ARG_SEARCH_PATHS PREPEND "-I") 35 | endif() 36 | 37 | if(APPLE AND CMAKE_OSX_SYSROOT) 38 | set(SDK_FLAGS "-sdk" "${CMAKE_OSX_SYSROOT}") 39 | elseif(WIN32) 40 | set(SDK_FLAGS "-sdk" "$ENV{SDKROOT}") 41 | elseif(CMAKE_SYSROOT) 42 | set(SDK_FLAGS "-sdk" "${CMAKE_SYSROOT}") 43 | endif() 44 | 45 | cmake_path(APPEND CMAKE_CURRENT_BINARY_DIR include 46 | OUTPUT_VARIABLE base_path) 47 | 48 | cmake_path(APPEND base_path ${header} 49 | OUTPUT_VARIABLE header_path) 50 | 51 | set(_AllSources $) 52 | set(_SwiftSources $) 53 | add_custom_command(OUTPUT ${header_path} 54 | DEPENDS ${_SwiftSources} 55 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} 56 | COMMAND 57 | ${CMAKE_Swift_COMPILER} -typecheck 58 | ${ARG_SEARCH_PATHS} 59 | ${_SwiftSources} 60 | ${SDK_FLAGS} 61 | -module-name "${ARG_MODULE_NAME}" 62 | -cxx-interoperability-mode=default 63 | -emit-clang-header-path ${header_path} 64 | COMMENT 65 | "Generating '${header_path}'" 66 | COMMAND_EXPAND_LISTS) 67 | 68 | # Added to public interface for dependees to find. 69 | target_include_directories(${target} PUBLIC ${base_path}) 70 | # Added to the target to ensure target rebuilds if header changes and is used 71 | # by sources in the target. 72 | target_sources(${target} PRIVATE ${header_path}) 73 | endfunction() 74 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/cmake/modules/InitializeSwift.cmake: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | # Compute the name of the architecture directory on Windows from the CMake 9 | # system processor name. 10 | function(_swift_windows_arch_name output_variable_name target_arch) 11 | if(NOT WIN32) 12 | return() 13 | endif() 14 | 15 | if("${target_arch}" STREQUAL "AMD64") 16 | set("${output_variable_name}" "x86_64" PARENT_SCOPE) 17 | elseif("${target_arch}" STREQUAL "ARM64") 18 | set("${output_variable_name}" "aarch64" PARENT_SCOPE) 19 | else() 20 | message(FATAL_ERROR "Unknown windows architecture: ${target_arch}") 21 | endif() 22 | endfunction() 23 | 24 | # Compute flags and search paths 25 | # NOTE: This logic will eventually move to CMake 26 | function(_setup_swift_paths) 27 | # If we haven't set the swift library search paths, do that now 28 | if(NOT SWIFT_LIBRARY_SEARCH_PATHS) 29 | if(CMAKE_OSX_SYSROOT) 30 | set(SDK_FLAGS "-sdk" "${CMAKE_OSX_SYSROOT}") 31 | endif() 32 | 33 | # Note: This does not handle cross-compiling correctly. 34 | # To handle it correctly, we would need to pass the target triple and 35 | # flags to this compiler invocation. 36 | execute_process( 37 | COMMAND ${CMAKE_Swift_COMPILER} ${SDK_FLAGS} -print-target-info 38 | OUTPUT_VARIABLE SWIFT_TARGET_INFO 39 | ) 40 | 41 | # extract search paths from swift driver response 42 | string(JSON SWIFT_TARGET_PATHS GET ${SWIFT_TARGET_INFO} "paths") 43 | 44 | string(JSON SWIFT_TARGET_LIBRARY_PATHS GET ${SWIFT_TARGET_PATHS} "runtimeLibraryPaths") 45 | string(JSON SWIFT_TARGET_LIBRARY_PATHS_LENGTH LENGTH ${SWIFT_TARGET_LIBRARY_PATHS}) 46 | math(EXPR SWIFT_TARGET_LIBRARY_PATHS_LENGTH "${SWIFT_TARGET_LIBRARY_PATHS_LENGTH} - 1 ") 47 | 48 | string(JSON SWIFT_TARGET_LIBRARY_IMPORT_PATHS GET ${SWIFT_TARGET_PATHS} "runtimeLibraryImportPaths") 49 | string(JSON SWIFT_TARGET_LIBRARY_IMPORT_PATHS_LENGTH LENGTH ${SWIFT_TARGET_LIBRARY_IMPORT_PATHS}) 50 | math(EXPR SWIFT_TARGET_LIBRARY_IMPORT_PATHS_LENGTH "${SWIFT_TARGET_LIBRARY_IMPORT_PATHS_LENGTH} - 1 ") 51 | 52 | string(JSON SWIFT_SDK_IMPORT_PATH ERROR_VARIABLE errno GET ${SWIFT_TARGET_PATHS} "sdkPath") 53 | 54 | foreach(JSON_ARG_IDX RANGE ${SWIFT_TARGET_LIBRARY_PATHS_LENGTH}) 55 | string(JSON SWIFT_LIB GET ${SWIFT_TARGET_LIBRARY_PATHS} ${JSON_ARG_IDX}) 56 | list(APPEND SWIFT_SEARCH_PATHS ${SWIFT_LIB}) 57 | endforeach() 58 | 59 | foreach(JSON_ARG_IDX RANGE ${SWIFT_TARGET_LIBRARY_IMPORT_PATHS_LENGTH}) 60 | string(JSON SWIFT_LIB GET ${SWIFT_TARGET_LIBRARY_IMPORT_PATHS} ${JSON_ARG_IDX}) 61 | list(APPEND SWIFT_SEARCH_PATHS ${SWIFT_LIB}) 62 | endforeach() 63 | 64 | if(SWIFT_SDK_IMPORT_PATH) 65 | list(APPEND SWIFT_SEARCH_PATHS ${SWIFT_SDK_IMPORT_PATH}) 66 | endif() 67 | 68 | # Save the swift library search paths 69 | set(SWIFT_LIBRARY_SEARCH_PATHS ${SWIFT_SEARCH_PATHS} CACHE FILEPATH "Swift driver search paths") 70 | endif() 71 | 72 | link_directories(${SWIFT_LIBRARY_SEARCH_PATHS}) 73 | 74 | if(WIN32) 75 | _swift_windows_arch_name(SWIFT_WIN_ARCH_DIR "${CMAKE_SYSTEM_PROCESSOR}") 76 | set(SWIFT_SWIFTRT_FILE "$ENV{SDKROOT}/usr/lib/swift/windows/${SWIFT_WIN_ARCH_DIR}/swiftrt.obj") 77 | add_link_options("$<$:${SWIFT_SWIFTRT_FILE}>") 78 | elseif(NOT APPLE) 79 | find_file(SWIFT_SWIFTRT_FILE 80 | swiftrt.o 81 | PATHS ${SWIFT_LIBRARY_SEARCH_PATHS} 82 | NO_CACHE 83 | REQUIRED 84 | NO_DEFAULT_PATH) 85 | add_link_options("$<$:${SWIFT_SWIFTRT_FILE}>") 86 | endif() 87 | endfunction() 88 | 89 | _setup_swift_paths() 90 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/include/fibonacci/fibonacci.h: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | #ifndef FIBONACCI_FIBONACCI_H 13 | #define FIBONACCI_FIBONACCI_H 14 | 15 | int fibonacci_cpp(int x); 16 | 17 | #endif // FIBONACCI_FIBONACCI_H 18 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/include/fibonacci/module.modulemap: -------------------------------------------------------------------------------- 1 | module Fibonacci { 2 | header "fibonacci.h" 3 | } 4 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/lib/fibonacci/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | add_library(fibonacci STATIC fibonacci.swift fibonacci.cpp) 9 | set_target_properties(fibonacci PROPERTIES Swift_MODULE_NAME "SwiftFibonacci") 10 | target_compile_options(fibonacci PUBLIC 11 | "$<$:-cxx-interoperability-mode=default>") 12 | 13 | # Generate a C++ header from Swift sources. This is automatically added to the 14 | # fibonacci target. The target will regenerate the header file when any of the 15 | # Swift sources change. Clang detects that the C++ file depends on the header, 16 | # and tells Ninja about this dependency in the depfile. 17 | # This function is implemented in cmake/modules/AddSwift.cmake. 18 | _swift_generate_cxx_header(fibonacci 19 | fibonacci/fibonacci-swift.h 20 | SEARCH_PATHS "${PINGPONG_INCLUDE_DIR}") 21 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/lib/fibonacci/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | #include "fibonacci/fibonacci-swift.h" 13 | #include 14 | 15 | int fibonacci_cpp(int x) { 16 | std::cout << "x [cpp]: " << x << std::endl; 17 | if (x <= 1) return 1; 18 | return SwiftFibonacci::fibonacciSwift(x - 1) + SwiftFibonacci::fibonacciSwift(x - 2); 19 | } 20 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/lib/fibonacci/fibonacci.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | import Fibonacci 13 | 14 | public func fibonacciSwift(_ x: CInt) -> CInt { 15 | print("x [swift]: \(x)") 16 | if x <= 1 { 17 | return 1 18 | } 19 | return fibonacci_cpp(x - 1) + fibonacci_cpp(x - 2) 20 | } 21 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2023 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | add_executable(fibonacci_swift fibonacci.swift) 9 | target_link_libraries(fibonacci_swift PRIVATE fibonacci) 10 | 11 | add_executable(fibonacci_cpp fibonacci.cpp) 12 | target_link_libraries(fibonacci_cpp PRIVATE fibonacci) 13 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/src/fibonacci.cpp: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | #include "fibonacci/fibonacci-swift.h" 13 | #include 14 | 15 | int main(int argc, char ** argv) { 16 | std::cout << SwiftFibonacci::fibonacciSwift(5) << std::endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /3_bidirectional_cxx_interop/src/fibonacci.swift: -------------------------------------------------------------------------------- 1 | //===----------------------------------------------------------------------===// 2 | // 3 | // This source file is part of the Swift open source project 4 | // 5 | // Copyright (c) 2023 Apple Inc. and the Swift project authors. 6 | // Licensed under Apache License v2.0 with Runtime Library Exception 7 | // 8 | // See https://swift.org/LICENSE.txt for license information 9 | // 10 | //===----------------------------------------------------------------------===// 11 | 12 | import Fibonacci 13 | 14 | print(fibonacci_cpp(5)) 15 | -------------------------------------------------------------------------------- /4_swift_macros/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2024 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | cmake_minimum_required(VERSION 3.22...3.29) 9 | 10 | project(StringifyMacroExample 11 | LANGUAGES Swift) 12 | 13 | include(ExternalProject) 14 | 15 | # Build the macros 16 | # 17 | # Macros must run on the same machine doing the compiling, not the one that 18 | # CMake is configured to build for. In order to support cross-compiling, we use 19 | # ExternalProject to invoke CMake again. This project assumes that the compiler 20 | # in toolchain is configured to compile for the builder by default. Otherwise, 21 | # you will need to set the `CMAKE_Swift_COMPILER_TARGET` to the builder triple. 22 | ExternalProject_Add(StringifyMacro 23 | SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/StringifyMacro" 24 | INSTALL_COMMAND "") 25 | ExternalProject_Get_Property(StringifyMacro BINARY_DIR) 26 | if(CMAKE_HOST_WIN32) 27 | set(StringifyMacroPath "${BINARY_DIR}/StringifyMacro.exe#StringifyMacro") 28 | else() 29 | set(StringifyMacroPath "${BINARY_DIR}/StringifyMacro#StringifyMacro") 30 | endif() 31 | 32 | add_executable(HelloMacros main.swift) 33 | add_dependencies(HelloMacros StringifyMacro) 34 | target_compile_options(HelloMacros PRIVATE -load-plugin-executable "${StringifyMacroPath}") 35 | -------------------------------------------------------------------------------- /4_swift_macros/StringifyMacro/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2024 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | 8 | cmake_minimum_required(VERSION 3.22...3.29) 9 | 10 | project(StringifyMacro 11 | LANGUAGES Swift) 12 | 13 | # We use FetchContent to download and build SwiftSyntax. Unlike ExternalProject, 14 | # FetchContent does not re-invoke CMake, and the build graphs are merged. This 15 | # exposes the variables and build targets in SwiftSyntax to our Macro project. 16 | # Everything in this project is isolated, so you can have macros that require 17 | # different versions of SwiftSyntax. They won't be able to link eachother, but 18 | # will work together as imported by the compiler. 19 | include(FetchContent) 20 | FetchContent_Declare(SwiftSyntax 21 | GIT_REPOSITORY https://github.com/apple/swift-syntax.git 22 | GIT_TAG 84a4bedfd1294f6ee18e6dc9ad70df55fa6230f6) 23 | FetchContent_MakeAvailable(SwiftSyntax) 24 | 25 | add_executable(StringifyMacro macro.swift) 26 | target_compile_options(StringifyMacro PRIVATE -parse-as-library) 27 | target_link_libraries(StringifyMacro 28 | SwiftSyntax 29 | SwiftSyntaxMacros 30 | SwiftCompilerPlugin) 31 | -------------------------------------------------------------------------------- /4_swift_macros/StringifyMacro/macro.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | import SwiftSyntaxMacros 3 | import SwiftCompilerPlugin 4 | 5 | public struct StringifyMacro: ExpressionMacro { 6 | public static func expansion( 7 | of node: some FreestandingMacroExpansionSyntax, 8 | in context: some MacroExpansionContext 9 | ) throws -> ExprSyntax { 10 | guard let arg = node.arguments.first, 11 | node.arguments.count == 1 else { 12 | throw CustomError("stringify requires exactly one argument") 13 | } 14 | return "(\(arg), \(literal: arg.description))" 15 | } 16 | } 17 | 18 | @main 19 | struct MacroPlugin: CompilerPlugin { 20 | let providingMacros: [Macro.Type] = [ 21 | StringifyMacro.self, 22 | ] 23 | } 24 | 25 | struct CustomError: Error, CustomStringConvertible { 26 | var msg: String 27 | init(_ msg: String) { self.msg = msg } 28 | var description: String { self.msg } 29 | } 30 | -------------------------------------------------------------------------------- /4_swift_macros/main.swift: -------------------------------------------------------------------------------- 1 | @freestanding(expression) 2 | public macro stringify(_ value: T) -> (T, String) = #externalMacro(module: "StringifyMacro", type: "StringifyMacro") 3 | 4 | print(#stringify(1 + 3)) 5 | -------------------------------------------------------------------------------- /4_swift_macros/readme.md: -------------------------------------------------------------------------------- 1 | # Stringify Macro Example 2 | 3 | This project demonstrates building and using a Swift macro in CMake. 4 | 5 | ## Requirements 6 | - Swift 5.9 (5.9.0+ macOS, 5.9.1 Windows and Linux) 7 | 8 | ## Build Instructions 9 | 10 | ```sh 11 | > mkdir build && cd build 12 | > cmake -G 'Ninja' ../ 13 | > ninja 14 | > ./HelloMacros 15 | (4, "1 + 3") 16 | ``` 17 | 18 | ## Description 19 | 20 | Macros must build for the local machine doing the building, not the machine 21 | you're building for because the compiler executes them. It's important to 22 | consider the macro as a separate project from the main part of the codebase if 23 | there is any chance you will want to cross-compile the project. 24 | 25 | We can manually invoke CMake twice, once to build the macro, then again to build 26 | the actual project for whatever platform we're building for, but that isn't very 27 | convenient. Instead, we use `ExternalProject_Add` to include the macro project 28 | which invokes compile 29 | 30 | ```cmake 31 | ExternalProject_Add(StringifyMacro 32 | SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/StringifyMacro" 33 | INSTALL_COMMAND "") 34 | ExternalProject_Get_Property(StringifyMacro BINARY_DIR) 35 | string(StringifyMacroPath "${BINARY_DIR}/StringifyMacro#StringifyMacro") 36 | ``` 37 | 38 | Technically, neither the compiler nor CMake know the triple for the build 39 | machine. This is normal, but inconvenient. We are assuming that the Swift 40 | compiler is configured to compile for the build machine by default. 41 | `ExternalProject_Add` doesn't forward variables from the current project into 42 | the external project, which is normally a pain-point of external projects, but 43 | in this case, is exactly what we want. 44 | 45 | In the macro project, we need to import SwiftSyntax to access the macro 46 | libraries. Since SwiftSyntax and the macro are built to run in the same 47 | environment, we can use `FetchContent` to merge the build graphs and build the 48 | entire macro project as one. 49 | ```cmake 50 | FetchContent_Declare(SwiftSyntax 51 | GIT_REPOSITORY https://github.com/apple/swift-syntax.git 52 | GIT_TAG 247e3ce379141f81d56e067fff5ff13135bd5810) 53 | FetchContent_MakeAvailable(SwiftSyntax) 54 | ``` 55 | 56 | Then it's just a matter of linking our macro executable against the needed 57 | libraries. 58 | 59 | ```cmake 60 | add_executable(StringifyMacro macro.swift) 61 | target_compile_options(StringifyMacro PRIVATE -parse-as-library) 62 | target_link_libraries(StringifyMacro 63 | SwiftSyntax 64 | SwiftSyntaxMacros 65 | SwiftCompilerPlugin) 66 | ``` 67 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This source file is part of the Swift open source project 2 | # 3 | # Copyright (c) 2025 Apple Inc. and the Swift project authors. 4 | # Licensed under Apache License v2.0 with Runtime Library Exception 5 | # 6 | # See https://swift.org/LICENSE.txt for license information 7 | # ============================================================================= 8 | # This file configure testing that each project configures and builds with 9 | # ctest. 10 | # It is not meant for configuring and building each project. 11 | 12 | cmake_minimum_required(VERSION 3.22) 13 | project(SwiftCMakeExamples LANGUAGES NONE) 14 | 15 | include(CTest) 16 | 17 | function(add_cmake_test name source_dir) 18 | cmake_parse_arguments(PARSE_ARGV 2 ARG "" "CMAKE_VERSION" "" ) 19 | if(NOT ARG_CMAKE_VERSION) 20 | set(ARG_CMAKE_VERSION 3.22) 21 | endif() 22 | 23 | if(${CMAKE_VERSION} VERSION_LESS ${ARG_CMAKE_VERSION}) 24 | message(STATUS "Skipping ${name} -- CMake version too old: ${CMAKE_VERSION} < ${ARG_CMAKE_VERSION}") 25 | return() 26 | endif() 27 | 28 | add_test(NAME "${name}-configure" 29 | COMMAND ${CMAKE_COMMAND} 30 | -G ${CMAKE_GENERATOR} 31 | -B "${name}-build" 32 | -S "${CMAKE_CURRENT_SOURCE_DIR}/${source_dir}" 33 | -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}) 34 | add_test(NAME "${name}-build" COMMAND 35 | ${CMAKE_COMMAND} --build "${name}-build") 36 | set_tests_properties("${name}-build" PROPERTIES DEPENDS "${name}-configure") 37 | endfunction() 38 | 39 | add_cmake_test(SingleExecutable 1_single_executable) 40 | add_cmake_test(ExecutableLibrary 2_executable_library) 41 | add_cmake_test(BidirectionalCxxInterop 3_bidirectional_cxx_interop 42 | CMAKE_VERSION 3.26) 43 | add_cmake_test(SwiftMacros 4_swift_macros) 44 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Swift CMake Examples 2 | 3 | ## How to submit a bug report 4 | 5 | Please ensure to specify the following: 6 | 7 | * Swift-CMake-Examples commit hash 8 | * Platform (Windows, macOS, Linux) 9 | * CMake version 10 | * Swift version 11 | * Clang version 12 | * Simple steps to reproduce 13 | * Failing CMake command invocation 14 | 15 | ## How to submit a new example 16 | 17 | Please keep examples self-contained; each example should be self-contained and 18 | not require parts from other examples. If a new example requires additional 19 | library or tool support from the system, the additional requirement should be 20 | indicated clearly. 21 | 22 | At this time, examples require [Swift](https://github.com/apple/swift), 23 | [CMake](https://github.com/kitware/cmake), and 24 | [Ninja](https://github.com/ninja-build/ninja), although some may have 25 | requirements for other compilers. 26 | 27 | To contribute new examples, please open a pull request at 28 | https://github.com/swiftlang/swift-cmake-examples. 29 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Swift CMake Examples 2 | 3 | This repository contains examples for using CMake to build Swift with different 4 | project layouts, including using CMake to build pure-Swift projects, and 5 | projects that use Swift-C++ interoperability. 6 | 7 | ## Requirements 8 | 9 | The projects in this repository have been tested with the 5.7.3 Linux container, 10 | as well as with the 5.7 compiler toolchain on macOS. For some of the examples 11 | with more advanced usage, you may need a newer CMake than what is shipped by 12 | the packages in your Linux distro. 13 | 14 | - CMake 3.22+\* 15 | - Ninja 1.5+ 16 | - Swift 5.7+\* 17 | 18 | \* Unless noted otherwise. 19 | 20 | These projects build with the Ninja generator (e.g `cmake -G 'Ninja' ...`) and 21 | likely do not work with the other generators. 22 | 23 | ## Single Executable 24 | 25 | Directory: `1_single_executable` 26 | 27 | This project demonstrates creating a simple executable written in Swift. 28 | 29 | ## Executable with Library 30 | 31 | Directory: `2_executable_library` 32 | 33 | This project demonstrates creating a single executable that links against a 34 | Swift library. 35 | 36 | ## Bi-directional Swift/C++ Interop 37 | 38 | Directory: `3_bidirectional_cxx_interop` 39 | 40 | This project demonstrates mixing Swift and C++ in a library using the Swift/C++ 41 | interoperability in Swift 5.9. Requires CMake 3.26, Swift 5.9, and Clang 11 or 42 | newer, or Apple Clang shipped in Xcode 12 or newer. 43 | 44 | Requires: 45 | 46 | - CMake 3.26 47 | - Swift 5.9 48 | - Clang 11 or Apple Clang in Xcode 12 or newer 49 | 50 | ## Swift Macros 51 | 52 | Directory: `4_swift_macros` 53 | 54 | This project demonstrates how to build a custom macro in a CMake-based project 55 | using the Swift macro support introduced in Swift 5.9. 56 | 57 | Requires: 58 | 59 | - Swift 5.9 (macOS: Swift 5.9.0, Windows and Linux: Swift 5.9.1) 60 | 61 | # Testing 62 | 63 | Tests are run with `ctest`, configured with the CMakeLists at the top-level. 64 | 65 | ```sh 66 | cmake -G Ninja -B build -S . 67 | cd build 68 | ctest -j --output-on-failure 69 | ``` 70 | 71 | When you add a test, add it to the top-level CMakeLists file and re-run CMake 72 | from the test directory to ensure that the CTest files are updated 73 | appropriately before trying to run the tests. 74 | 75 | ```sh 76 | cmake . 77 | ctest -j --output-on-failure 78 | ``` 79 | --------------------------------------------------------------------------------