Android NDK学习(7)NDK测试时遇到的问题:C与C++互相调用

贴代码:

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++代码中。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章