Monday, September 5, 2022

[SOLVED] cmake generator expression for target architecture?

Issue

Is there a modern approach to use target architecture within a condition for a generator expression in CMake? There are some href="https://stackoverflow.com/questions/11944060/how-to-detect-target-architecture-using-cmake">answers that are somewhat outdated. I am looking for a modern or at least very robust and reliable custom script for using target architecture within a generator expression. The docs do not seem to contain that kind of info.

One of the ideas for a workaround I see is to use $<<STRING:MY_DETECTED_ARCH:ARCH_ARM>:src_for_arm.cpp>


Solution

I checked a solution from this answer and it worked.

cmake_minimum_required(VERSION 3.14.2 FATAL_ERROR)
project(cmake_target_arch)

set(CMAKE_CXX_STANDARD 17)
include(TargetArch.cmake)

target_architecture(TARGET_ARCH)
message(STATUS "target_architecture: ${TARGET_ARCH}")

add_executable(cmake_target_arch
        main.cpp
        $<$<STREQUAL:"${TARGET_ARCH}","x86_64">:x86_64.cpp>
        $<$<STREQUAL:"${TARGET_ARCH}","i386">:i386.cpp>
        $<$<STREQUAL:"${TARGET_ARCH}","armv7">:armv7.cpp>
        )

main.cpp

#include <iostream>

#include <string>

extern std::string hello_message();

int main()
{
    std::cout << hello_message() << std::endl;
    return 0;
}

i386.cpp


#include <string>

std::string hello_message()
{
    return "Hello i386!";
}

Example output for i386 binary:

C:\Users\serge\dev\repos\cmake_target_arch\cmake-build-release-visual-studio-win32\cmake_target_arch.exe
Hello i386!

I guess one can come up with a CMake Macro to wrap strings comparison



Answered By - Sergey Kolesnik
Answer Checked By - Pedro (WPSolving Volunteer)