PC机使用CMake编译Android可执行文件

说明

系统环境:mac os
运行条件: 安装cmake 和 下载ndk

创建文件

源文件 hello.cpp

#include
int main(){
    printf("hello world \n");
    return 0;
}

CMakeCache.txt 文件

cmake_minimum_required(VERSION 3.7)
#include(/Users/Shared/ShareLib/Android/sdk/ndk-bundle/build/cmake/android.toolchain.cmake)
# 打印当前的环境
if(ANDROID)
    message(STATUS "ANDROID")
elseif(APPLE)
    message(STATUS "APPLE")
elseif(WIN32)
    message(STATUS "WIN32")
elseif(UNIX)
    message(STATUS "UNIX")
else()
    message(FATAL_ERROR "OTHER")
endif()
 
add_executable(hello hello.cpp)
target_include_directories(hello PRIVATE .)


# cmake  -DCMAKE_TOOLCHAIN_FILE=/Users/Shared/ShareLib/Android/sdk/ndk-bundle/build/cmake/android.toolchain.cmake ..

编译工程

创建build目录并进入

在build目录下执行cmake

cmake  -DCMAKE_TOOLCHAIN_FILE=/Users/Shared/ShareLib/Android/sdk/ndk-bundle/build/cmake/android.toolchain.cmake ..

其中"/Users/Shared/ShareLib/Android/sdk/ndk-bundle/build/cmake/android.toolchain.cmake"是本机机器ndk安装交互编译的cmake配置
输出

-- ANDROID_PLATFORM not set. Defaulting to minimum supported version
16.
-- Check for working C compiler: /Users/Shared/ShareLib/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang
-- Check for working C compiler: /Users/Shared/ShareLib/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Users/Shared/ShareLib/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang++
-- Check for working CXX compiler: /Users/Shared/ShareLib/Android/sdk/ndk-bundle/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- ANDROID
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/wangshengxing/project/c/ndkcmake/hello/build

此时执行 make ,输出

Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/hello.cpp.o
[100%] Linking CXX executable hello
[100%] Built target hello
image

以上hello即为可在安卓上执行的文件

执行文件

将hello文件push到手机的/data/local/tmp/目录下

运行文件

adb shell
cd /data/local/tmp/
./hello

则得到以下输出


image

你可能感兴趣的:(PC机使用CMake编译Android可执行文件)