貼代碼:
test.h
int adds(int a,int b);
int subs(int a,int b);
test.c
#include "test.h"
int adds(int a,int b)
{
return (a-b);
}
int subs(int a,int b)
{
return (a+b);
}
com_ycan_ycantestlib.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_ycan_ycantestlib */
#ifndef _Included_com_ycan_ycantestlib
#define _Included_com_ycan_ycantestlib
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_ycan_ycantestlib
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_ycan_ycantestlib_add
(JNIEnv *, jobject, jint, jint);
/*
* Class: com_ycan_ycantestlib
* Method: sub
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_ycan_ycantestlib_sub
(JNIEnv *, jobject, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
com_ycan_ycantestlib.cpp
include "com_ycan_ycantestlib.h"
#ifdef __cplusplus
extern "C" {
#endif
#include "test.h"
#ifdef __cplusplus
}
#endif
JNIEXPORT jint JNICALL Java_com_ycan_ycantestlib_add
(JNIEnv *evn, jobject thiz, jint a, jint b)
{
int c =adds(a,b);
return c;
}
JNIEXPORT jint JNICALL Java_com_ycan_ycantestlib_sub
(JNIEnv *evn, jobject thiz, jint a, jint b)
{
int c =subs(a,b);
return c;
}
Android.mk
#Android.mk和需要編譯的源文件在同一目錄下
#
LOCAL_PATH:= $(call my-dir)
#源文件列表
#
common_SRC_FILES :=\ test.c \ com_ycan_ycantestlib.cpp
#頭文件列表
#
common_C_INCLUDES :=\ test.h \ com_ycan_ycantestlib.h
#模塊開始
#
include $(CLEAR_VARS)
#源文件列表
#
LOCAL_SRC_FILES := $(common_SRC_FILES)
#頭文件列表
#
LOCAL_C_INCLUDES += $(common_C_INCLUDES)
#生成的程序名
#
LOCAL_MODULE:= com_ycan_ycantestlib
#此處有三個選擇:可執行程序,動態庫,靜態庫
#
include $(BUILD_SHARED_LIBRARY)
這是c++調用c的情況,解決問題的關鍵就是com_ycan_ycantestlib.cpp中的這段:
#ifdef __cplusplus
extern "C" {
#endif
#include "test.h"
#ifdef __cplusplus
}
#endif
反過來,也是一樣的,需要注意的是這段只能加在c++代碼中。