Search code examples
c++compilationjava-native-interfacejavah

Is there a way to make sure a C++ .h matches the corresponding C++ .cpp file?


The code in question is a JNI interface between a Java and a native code. The h file is produced by the javah utility, whereas the cpp file is created by human.

If the Java part is renamed then javah produces function prototypes with the corresponding names, like it should. However, nothing makes sure the functions in the cpp file are renamed as well - all compiles as usual. The problem will only arise when the Java code invokes the native API at runtime.

How could one catch a mismatch between the h file produced by javah and the implementation cpp file produced by human during the compilation?


Solution

  • How about referring to the generated function declarations somewhere in the C++ code?

    E.g. in (say) generated_check.cpp create a function that calls your prototypes with dummy parameters (but never call it):

    #include "generated.h" // your javah output
    
    static void neverCalled() {
         // Compiler errors here mean that the functions have changed:
         Java_com_example_package_MyClass_myFunc1(0, 0, 0);
         Java_com_example_package_MyClass_myFunc2(0);
    }
    

    Edit, in response to your comments:

    Another (or complementary) approach would be to create a script that runs as part of your build process and have it back up the old generated.h before javah is run, and cause a build error if the new generated.h is different to the old one. It could even run a diff program to give you an error message to pinpoint the change.