unable to link between c and c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeevs
    New Member
    • Aug 2007
    • 1

    unable to link between c and c++

    I have a class whose member I need to access in c prog.
    I have defined the class object as extern.

    when I tried to access the class member in c it says undefine reference.

    where as I'm able to access the same class members in different places.
    please help me
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You will not be able to access any class members from C because a class is a C++ construct that C is unaware of.

    What you can do is declare functions with C naming convention in a C++ file

    Header
    [code=cpp]
    #ifdef __cplusplus
    extern "C" {
    #endif

    extern void MyFunction(void );

    #ifdef __cplusplus
    }
    #endif
    [/code]
    cpp code
    [code=cpp]
    #include "header"

    void MyFunction(void )
    {
    // Code here that accesses the class
    }
    [/code]

    c code
    [code=c]
    #include "header"

    void SomeFunction(vo id)
    {
    MyFunction();
    }
    [/code]
    This enables C code to call into C++ modules, you then put the C++ code (code accessing classes for instance) inside the function with the C naming convention.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Continuing Banfa's reply, you can write a function (extern "C") in C++ that calls the member function of the class and then you can call this function from C.

      These are called buck-passer functions and are quite common.

      Comment

      Working...