Search code examples
c++copencvlinkagesift

Linking Rob Hess's SIFT library (in C, using OpenCV) with C++


I'm trying to use Rob Hess's SIFT library in my C++ project. I've looked through (the code of) other SIFT implementations, but this one seemed most phase-divided like the original Lowe's paper and also uses OpenCV which I am familiar with, so I chose this one.

Unfortunately, I've had only trouble since I've tried using it in C++. The library is originally written in C with OpenCV.

I have tried compiling my code both with and without surrounding the C library include-s with extern, but neither works. I think I have diagnosed what the problems are in both cases, but I don't know how to solve them and I would very much appreciate any help.

Problems (or at least, what I think the problems are):

  • withouth extern: doesn't work because of C++ name-mangling (I've checked, and of course all the function names are decorated)

  • with extern : doesn't work because OpenCV can detect weather it's compiled for C or C++. There are no linkage problems with any of the SIFT library functions, but now OpenCV includes C++ headers, and since in the main program it's ultimately included in the extern block, I get (literally hundereds) of errors like these:

    /usr/local/include/opencv2/core/mat.hpp:2361: error: template with C linkage

I have been trying to make this work for the last couple of days, so if anyone has tried to work with the same SIFT library in C++ or has experienced similar problems with a different library, help would be most appreciated.


Solution

  • Looks like I've managed to find quite a nice solutions. Two ways, easy and elegant:

    Easy:

    Just include all the OpenCV headers used in the library (and any other OpenCV headers needed) before the extern "C" section including all the SIFT library headers.

    Elegant

    In all the library headers, add the sections extern "C" around all the code except the OpenCV includes, like so:

    // OpenCV includes:
    #include "cxcore.h"
    #include ....
    
    #if __cplusplus
    extern "C" {
    #endif
    
    ...
    function definitions in the header file
    ...
    
    #if __cplusplus
    }
    #endif
    

    Now all the library includes can be #included directly in the C++ code without the extern "C". The OpenCV libraries compile correctly for C/C++ (depending on the compiler), and the relative order of the additional OpenCV includes and the SIFT library includes doesn't matter.