android - 如何在 ANDROID NDK 中从 C 文件调用 CPP 文件中的函数,反之亦然?

标签 android c++ c android-ndk

我无法从 c 文件调用 cpp 文件中的函数,也无法从 ndk 本身的 cpp 文件调用 c 文件中的函数。

我也尝试过使用 extern "C"{}。

粘贴我试过的代码以供引用。

CFileCallingCpp.c:

#include "CFileCallingCpp.h"
//#include "custom_debug.h"
#include "CppFile.h"





void tempFunc() {

}

void printTheLogs() {
    //Its not possible to make use of the CPP class in c file
//  CCustomDebug cls;
//  cls.printErrorLog("This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
//  cls.printErrorLog("EXAMPLE", "This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
    printTheLogs1();
//  tempFunc();
}

CFileCallingCpp.h:

#ifndef _CFILECALLINGCPP_H_
#define _CFILECALLINGCPP_H_

void printTheLogs();


#endif

Cpp文件.cpp:

#include "CppFile.h"
#include "custom_debug.h"
#include "CFileCallingCpp.h"

void printTheLogs1() {
    CCustomDebug::printErrorLog("This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
    CCustomDebug::printErrorLog("EXAMPLE", "This is the error log %d %s", 54321, "aaaaaaaaaaaaaaaaaa");
}

#if defined(__cplusplus)
extern "C" {
#endif

void callCFileFunc() {
    printTheLogs();
//  printTheLogs1();
}


#if defined(__cplusplus)
}
#endif

CppFile.h:

#ifndef _CPPFILE_H_
#define _CPPFILE_H_

void printTheLogs1();


#endif

我遇到的错误:

    sh-4.1$ /cygdrive/c/Android/android-ndk/ndk-build
    SharedLibrary  : libJNIExInterface.so
    D:/EclipseWorkspace/NativeExample/obj/local/armeabi/objs-debug/JNIExInterface/CppFile.o: In function `callCFileFunc':
    D:/EclipseWorkspace/NativeExample/jni/CppFile.cpp:15: undefined reference to `printTheLogs()'
    D:/EclipseWorkspace/NativeExample/obj/local/armeabi/objs-debug/JNIExInterface/CFileCallingCpp.o: In function `printTheLogs':
    D:/EclipseWorkspace/NativeExample/jni/CFileCallingCpp.c:18: undefined reference to `printTheLogs1'
    collect2: ld returned 1 exit status
    make: *** [/cygdrive/d/EclipseWorkspace/NativeExample/obj/local/armeabi/libJNIExInterface.so] Error 1
    sh-4.1$

如果有人知道如何从 ANDROID-NDK 中的 c 代码调用 cpp 代码,请告诉我。

问候,
S苏曼185

最佳答案

如果你从一个c文件中定义的cpp文件中调用一个函数,你可以只使用

extern "C" void c_func(); // definition

// from a cpp file
c_func();

你可以反其道而行之,从c文件调用cpp文件中实现的函数

// implemnatation in cpp file
extern "C" void cpp_func()
{
    // c++ code allowed here
}

// declaration in .h file
#ifdef _CPLUSPLUS
extern "C" void cpp_func();
#else
extern void cpp_func();
#endif

// from the c file
....
cpp_func();
.....

关于android - 如何在 ANDROID NDK 中从 C 文件调用 CPP 文件中的函数,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255516/

相关文章:

c++ - 在链表初学者中创建多个节点

c++ - 告诉您 C++ 项目中需要哪些源文件的工具?

c++ - 如何在 C/C++ 中读取未知维度的数据文件

c - 是否可以将 char 指针分配给 float 值?

java - Android Studio Onbackpressed

android - 键错误的 fragment 不再存在

java - 如何基于设备切换加速度计 Axis ?

android - 是否可以使用 OneSignal 获取设备 token

c++ - Ubuntu : apt-get install <package> equivalent in C++ apt-pkg library

c - 在 C 中使用 Fread