CMake Universal Binary - arch depending compile options

1.4k Views Asked by At

I'm building a MacOS Universal Binary using set (CMAKE_OSX_ARCHITECTURES arm64 x86_64) - working fine so far.

But x86_64 should have other compile options than arm64.

Is there something like:

if (CURRENT_TARGET MATCHES x86_64)
    add_compile_options (-Wall -Ofast -ffast-math -fno-exceptions)
else()
    add_compile_options (-Wall -O3 -fno-exceptions)
endif()

Or any other solution?

3

There are 3 best solutions below

0
On

You can do this via the XCODE_ATTRIBUTE_* property, though this will unfortunately tie your project to XCode. If you have a target my_target to which you'd like to add multi-arch-specific flags, you would write:

cmake_minimum_required(VERSION 3.20)
project(example)

add_executable(my_target main.cpp)
set_target_properties(
  my_target
  PROPERTIES
    XCODE_ATTRIBUTE_PER_ARCH_CFLAGS_x86_64 "-DBUILDING_FOR_X86_64"
    XCODE_ATTRIBUTE_PER_ARCH_CFLAGS_arm64 "-DBUILDING_FOR_ARM64"
)

Then you would build with:

$ cmake -G Xcode -S . -B build -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64"
$ cmake --build build --config Release
1
On

You can prefix flags for a specific architecture with -Xarch_arm64 or -Xarch_x86_64. Your example would be:

add_compile_options (-Wall -Xarch_arm64 -O3 -Xarch_x86_64 -Ofast -Xarch_x86_64 -ffast-math -fno-exceptions)
0
On

You can add [arch=x] to the end of any property to give it architecture specific settings. The formatting that worked for me was:

set_target_properties(${TARGET} PROPERTIES
            XCODE_ATTRIBUTE_OTHER_LDFLAGS[arch=x86_64] "${IPP_LIB_DIR}/libippi.a $(inherited)"
            XCODE_ATTRIBUTE_OTHER_LDFLAGS[arch=arm64] "-framework Accelerate $(inherited)")

Note that without $(inherited), this will overwrite the non-architecture specific build settings. So in the above example, without $(inherited), libraries added with target_link_libraries() would not be linked.