How to write Cmake on Android Studio

Asked 1 years ago, Updated 1 years ago, 394 views

I would like to introduce C source code using Cmake on Android Studio, but when I run, I get the following error.
Java/Kotlin as a library would like to call main.cpp.
I'm sorry for the rudimentary question, but if you don't mind, please let me know.
environment:

  • OS:Windows 10
  • Android Studio: Chipmunk 2021.2.1.Patch1

File Configuration

  • main.cpp
  • a.cpp
  • a.h

Error Description:

 C/C++:../../../src/main/cpp/main.cpp:16: error: undefined reference to 'a()'

main.cpp

#include<jni.h>
# include "a.h"

external "C"
JNIEXPORT void JNICALL
Java_com_example_clibtest_MainActivity_main(JNIEnv*env,jobject thiz){
    a();
}

a.cpp

#include<jni.h>
external "C" JNIEXPORT void
a(){
}

a.h

#ifndef CLIBTEST_A_H
#define CLIBTEST_A_H


external void a();

#endif//CLIBTEST_A_H

CMakeLists.txt

cmake_minimum_required (VERSION 3.4.1)    

add_library(a SHARED src/main/cpp/a.cpp)
add_library (main SHARED src/main/cpp/main.cpp)

target_link_libraries(
        main
        a
        android
        log)


include_directories(src/main/cpp/)

android c++ c cmake

2022-12-14 05:32

1 Answers

If you do not want to publish the C/C++ function a directly to the Java/Kotlin layer, you do not need the extern "C" or JNIEXPORT.

a.cpp

#include<a.h>
voida(){
  // (Implementation)
}

add_library should be sufficient for one shared library (the substance loaded from the JJava/Kotlin layer).All the source code groups that make up the shared library are listed after the third argument.

CMakeLists.txt

add_library(main SHARED)
  src/main/cpp/main.cpp
  src/main/cpp/a.cpp)

target_link_libraries(
        main
        android
        log)


2022-12-14 08:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.