001_Android Studio使用CMake工具和C语言混合编译

1.官方例子

Android Studio到2.2版本之后,在新建工程时,界面上多了一个Include C++ Support的选项。勾选它之后将会创建一个默认的C++与JAVA混编的示例工程。下面简单介绍一下这个工程

1.1 新建工程

勾选"include C++ support",然后点击"next",选择“Empty Activity”,最后点击“Finish”,这样和C++混合编译的工程就创建完毕。
勾选C++
.
选择空

1.2 混和编译的差异

项目打开后选择“Project”选项查看目录结构,工程里多出了.externalNativeBuild文件夹、cpp文件夹、CMakeLists.txt,如下图:

3项

  • 这三项说明如下:

    1. externalNativeBuild文件夹:通过cmake工具编译输出的文件, 显示支持的各种硬件等信息。系统生成。
    2. cpp文件夹:存放C/C++代码文件,native-lib.cpp文件是该示例工程中自带的,可以根据自己需求修改。
    3. CMakeLists.txt文件:CMake工具编译C语言的脚本配置的文件。需要根据自己需求进行相应的修改。
  • app目录下的build.gradle文件中有两处不一样,如下图所示:
    !Build差异

  • MainActiviy文件中调用C++文件内容的方式如下图:

    • 前面表示加载哪个C++文件;
    • 后面表示对C++文件中的函数进行引用说明。
      调用方式
package com.zhoujiazhao.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(stringFromJNI());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
  • 此外,C++文件中的函数名要和自己工程的包名和引用的类名要对应,我的是Java_com_zhoujiazhao_myapplication_MainActivity
#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring

JNICALL
Java_com_zhoujiazhao_myapplication_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());
}

创建C源码

2.在其它工程中添加和C混合编译

2.1 创建“cpp"文件夹和“c"源码

这里文件名为“hello.c”

//
// Created by jiazhao on 2018-06-28.
//

#include <jni.h>


jint Java_com_zhoujiazhao_zhaoc_MainActivity_Add(
        JNIEnv *env,
        jobject obj, jint a, jint b) {
    return a + b;
}

build.gradle文件修改

2.2 build.gradle文件中添加如下代码:

        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
        
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }

build.gradle文件修改

2.3 创建CMakeLists.txt文件

这里部分代码可以从官方示例工程里面直接拷贝过来,进行修改,需根据C文件名进行修改,如下图所示:

CmakeLists文件修改

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
             hello

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             src/main/cpp/hello.c )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
                       hello

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

2.4 C文件中函数的调用的方法和官方示例工程类似,MainActivity文件如下:

package com.zhoujiazhao.zhaoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("hello");
    }

    private TextView mTextView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView)findViewById(R.id.hello_text_view);
        mTextView.setText("aaa:" + Integer.toString(Add(3, 5)));
    }

    public native int Add(int a, int b);
}

2.5生产xx.so库

点击菜单“Build -> Make project”生成.so文件

.so文件目录:app-build-intermediates-cmake-debug-obj

so库目录

写博客不容易,需要大家多多支持。想了解更多,本人也可以提供有赏服务
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值