Android Studio CMake 生成多个so

本文介绍了一个Android应用中加载并使用两个不同so库(one-lib和two-lib)的具体实现方式。通过CMakeLists.txt文件配置,实现了两个so库的独立编译与链接,并在Java层面对这些so库进行调用。每个so库提供了一个返回字符串的方法,最终在MainActivity中展示出调用结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生成多个so案例

这里stringFromJNIstringFromJNI11分别是调用one-lib和two-lib两个so

package com.test.ndkmoreso;

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("one-lib");
        System.loadLibrary("two-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()+"   two"+stringFromJNI11());
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
    public native String stringFromJNI11();
}

 

 

cpp的目录结构:

 

 

直接看1的CMakeLists.txt文件

cmake_minimum_required(VERSION 3.4.1)

#添加子目录,将会调用子目录中的CMakeLists.txt

SET(ONE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/one)
SET(TWO_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/main/cpp/two)

MESSAGE(STATUS “src  dir: ${CMAKE_CURRENT_SOURCE_DIR}”)

MESSAGE(STATUS “one  dir: ${ONE_PATH}”)
MESSAGE(STATUS “two  dir: ${TWO_PATH}”)

ADD_SUBDIRECTORY(${ONE_PATH})

ADD_SUBDIRECTORY(${TWO_PATH})

 

one的lib

2的CMakeLists.txt文件

cmake_minimum_required(VERSION 3.4.1)

#生成so动态库
ADD_LIBRARY(one-lib SHARED one.cpp)

target_link_libraries(one-lib log)

 

one.cpp

#include <jni.h>
#include <string>


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

 

 

 

two的lib

查看3的CMakeLists.txt文件

cmake_minimum_required(VERSION 3.4.1)

#生成so动态库
ADD_LIBRARY(two-lib SHARED two.cpp)

target_link_libraries(two-lib log)

 

two.cpp

#include <jni.h>
#include <string>


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

 

生成的结果如下

 

转载于:https://www.cnblogs.com/mingfeng002/p/7201034.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值