CMakelists.txt
add_library(node SHARED src/node.c)
target_link_libraries(nativelib ${node})
============================================
note.h
#ifdef __cplusplus
extern "C" {
#endif
#ifndef TESTDEMO_NODE_H
#define TESTDEMO_NODE_H
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
struct Node *previous;
} node_t;
typedef struct List {
struct Node *head;
struct Node *tail;
} list_t;
extern void list_init(list_t *list);
#endif //TESTDEMO_NODE_H
#ifdef __cplusplus
}
#endif
============================================
note.c
#include "node.h"
static node_t* creatNode(int data) {
node_t *pnode = malloc(sizeof(node_t));
pnode->data = data;
pnode->previous = NULL;
pnode->next = NULL;
return pnode;
}
void list_init(list_t *list){
list->head = creatNode(-1);
list->tail = creatNode(-1);
list->head->next = list->tail;
};
============================================
native-lib.cpp
#include <jni.h>
#include <string>
#include <assert.h>
#include <node.h>
extern "C" JNIEXPORT jstring JNICALL
Java_com_test_testdemo_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */) {
// std::string hello = "Hello";
char *str = "titles";
list_t list;
list_init(&list);
return env->NewStringUTF(str);
}
============================================
错误
C/C++: ld.lld: error: undefined symbol: list_init
C++ build system [build] failed while executing:
/Users/didi/Library/Android/sdk/cmake/3.22.1/bin/ninja \
-C \
/Users/didi/AndroidStudioProjects/TestDemo/app/.cxx/Debug/1j3s156k/arm64-v8a \
nativelib \
node
from /Users/didi/AndroidStudioProjects/TestDemo/app
at com.android.build.gradle.internal.cxx.process.ExecuteProcessKt.execute(ExecuteProcess.kt:274)
at com.android.build.gradle.internal.cxx.process.ExecuteProcessKt$executeProcess$1.invoke(ExecuteProcess.kt:106)
at com.android.build.gradle.internal.cxx.process.ExecuteProcessKt$executeProcess$1.invoke(ExecuteProcess.kt:104)
... 112 more
Caused by: com.android.ide.common.process.ProcessException: Error while executing process /Users/didi/Library/Android/sdk/cmake/3.22.1/bin/ninja with arguments {-C /Users/didi/AndroidStudioProjects/TestDemo/app/.cxx/Debug/1j3s156k/arm64-v8a nativelib node}
at com.android.build.gradle.internal.process.GradleProcessResult.buildProcessException(GradleProcessResult.java:73)
at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:48)
at com.android.build.gradle.internal.cxx.process.ExecuteProcessKt.execute(ExecuteProcess.kt:269)
... 129 more
Caused by: org.gradle.process.internal.ExecException: Process 'command '/Users/didi/Library/Android/sdk/cmake/3.22.1/bin/ninja'' finished with non-zero exit value 1
at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:415)
at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:46)
... 130 more