How to call a function in a CPP file from a C file and vice versa in ANDROID NDK?

I can not call the function in the cpp file from the c file, as well as the function in the c file from the cpp file in ndk itself.

I tried using extern "C" {}.

Paste the code I tried here for reference.

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 

Cppfile.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 

Errors I get:

  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$ 

Please let me know if anyone knows how to call cpp code from c code in ANDROID-NDK.

Respectfully,
SSuman185

+6
source share
2 answers

extern "C" should be in the header file included by the C source, and not in the C ++ source file. The same goes for the C header file contained in the C ++ source file.

+2
source

If you call a function from the cpp file that is defined in the c file, you can simply use

 extern "C" void c_func(); // definition // from a cpp file c_func(); 

You can do the return path by calling the imlpegeded function in the cpp file from the c file

 // 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(); ..... 
+8
source

Source: https://habr.com/ru/post/902294/


All Articles