[CMake] How to do platform specific setup?

Robert Dailey rcdailey.lists at gmail.com
Wed Jul 19 15:22:30 EDT 2017


So in one of my top level CMake scripts, I have this:

```
if( ANDROID )
    include( android )
    _setup_android_platform()
elseif( UNIX )
    include( unix )
    _setup_unix_platform()
endif()

if( CMAKE_CXX_COMPILER_ID STREQUAL "Clang" )
    include( clang )
    _setup_clang_toolchain()
elseif( CMAKE_CXX_COMPILER_ID STREQUAL "MSVC" )
    include( msvc )
    _setup_msvc_toolchain()
endif()
```

This allows me to set up various global things used by all targets
defined by CMake. An example of what android's does:

```
macro( _setup_android_platform )
    # Forward the android ABI from CMake to a custom variable for
portability to other toolchains
    if( CMAKE_ANDROID_ARCH_ABI )
        set( ANDROID_ABI ${CMAKE_ANDROID_ARCH_ABI} )
    endif()

    # Forcefully disable testing while cross compiling for Android
platform. It doesn't make sense
    # to build tests, since we can't run them natively. We build tests
on a separate platform.
    set( BUILD_TESTING OFF CACHE BOOL "Do not build unit tests when
cross compiling for Android" FORCE )

    android_ndk_import_module_cpufeatures()
    android_ndk_import_module_native_app_glue()

    # Export ANativeActivity_onCreate(),
    # Refer to: https://github.com/android-ndk/ndk/issues/381.
    set( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -u
ANativeActivity_onCreate" )

    add_definitions(
        -DANDROID
    )
endmacro()
```

And clang:

```
macro( _setup_clang_toolchain )
    # Disable certain clang warnings
    # These spam like crazy; disable for now
    add_compile_options(
        -Wno-inconsistent-missing-override
    )

    # Clang 3.8.0 on Ubuntu was failing with -Wno-expansion-to-defined.
    # Version 3.8.2 in NDK r14b seems ok with it.
    if( CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 3.8.2 )
        add_compile_options(
            -Wno-expansion-to-defined
        )
    endif()

    set( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS}
-Wl,--no-undefined" )
endmacro()
```

I feel like there is a better way. I recall there being some built-in
way to override CMake's platform specific setup modules, but I don't
know anything about it. Can someone offer some advice on if there is a
built in way to do this?


More information about the CMake mailing list