Combining C and C++ codes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • philipho
    New Member
    • Sep 2006
    • 1

    #1

    Combining C and C++ codes

    Hi all,

    I have an Opencv face detection code that is written in C. I am currently doing a face detection project that makes use of Euresys frame grabbers. The problem is the image acquisition codes for Euresys are all written in C++, and i have to pass the frames captured to the face detection program for real time face tracking.

    Will it be feasible to combine C and C++ codes?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Yes it is possible, but you will have a few problems to overcome.

    1. C can not use classes (seems obvious but I thought I'd mention it).

    2. C and C++ use different function calling conventions. C++ can be told use the C calling convention but C can not use the C++ calling convention.

    You will often see code like this in a header file

    Code:
    #ifdef  __cplusplus
    extern "C" {
    #endif
    
    // Header file definitions
    
    #ifdef __cplusplus
    }
    #endif
    This is used in a header file that contains the definitions for a C source file. All C++ compilers define __cplusplus when compiling C++ source files so basically what these directives do is tell the C++ compiler to use C calling convention for anything between the { and }. This allows the C++ and C csource code to call these functions.

    There are many tricks to pull with this, for instance you can declare a function in a C++ file with C calling convention, then C code can call that function but because it is in a C++ file it can use C++ features, like access to classes.

    I have worked on several projects that have mixed C and C++ code, it just takes a little care.

    Comment

    Working...