【CMake】Android native模块a调用native模块b,如何配置cmake?

Android项目中如何配置cmake,让module a的native代码调用module b的native代码?

打印路径

首先可以看看CMAKE_SOURCE_DIR的具体路径:

message("CMAKE_SOURCE_DIR :" + ${
    
    CMAKE_SOURCE_DIR})

定义子目录的路径

set(MODULE_A_DIR   ${
    
    CMAKE_SOURCE_DIR}/../../../../module-a/src/main/cpp)
message("MODULE_A_DIR :" + ${
    
    MODULE_A_DIR})

把子模块的cmakelists添加关联

接着根据自己项目的具体位置,找到实际上module a的代码路径。接着调用add_subdirectory,添加到对应的路径中。
add_subdirectory的主要作用是添加另外一个cmakelist到当前的cmakelisk的搜索目录中。

参考doc:https://cmake.org/cmake/help/latest/command/add_subdirectory.html

add_subdirectory( ${
    
    MODULE_A_DIR}  ${
    
    MODULE_A_DIR}/build)

这里需要注意的是,这种情境下使用add_subdirectory,它的第二个参数需要声明对应的build 后二进制文件的具体路径,不然无法编译链接通过。

添加源码文件搜索路径

include_directories(${
    
    MODULE_A_DIR})

参考doc:https://cmake.org/cmake/help/latest/command/include_directories.html

添加库的链接

到这里,需要把子module的库链接到主module,才能编译运行:

target_link_libraries(${
    
    CMAKE_PROJECT_NAME}
        # List libraries link to the target library
        android
        module_a
        log)

测试

子module

test.h

//
// Created by linshujie on 2024/3/18.
//

#ifndef CMAKEDEMO_TEST_H
#define CMAKEDEMO_TEST_H



//add cplusplus flag
#ifdef __cplusplus
extern "C" {
    
    
#endif

    void printnum(int a);

#ifdef __cplusplus
}
#endif


#endif //CMAKEDEMO_TEST_H

test.c

//
// Created by linshujie on 2024/3/18.
//
#include "stdio.h"
#include "android/log.h"
void printnum(int a) {
    
    
//    printf("%d\n", a);
    __android_log_print(ANDROID_LOG_DEBUG, "linshujie", "%d", a);
}

JNI代码:

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

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

运行,成功打印。

代码链接:https://github.com/ShujieLin/cmakedemo

猜你喜欢

转载自blog.csdn.net/Shujie_L/article/details/136808057