mixing c and c++ code in one project

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ekailan
    New Member
    • Oct 2010
    • 11

    mixing c and c++ code in one project

    I have a c++ project and i have a c code I need to mix them both in one solution .....I still get errors .
    I need the c code to be in one class and I need to call it from a c++ main()/
    any official technique?!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You can mix C and C++ coded but there's a trick to it.

    First, C++ has function overloading. That is, you can have muiltiple functions of the same name as long as the arguments are different.

    Second, C++ uses a decorator, or mangler, to hash a functions and it's arguiments to a unique symbol. This symbol, which may look like MHG_FYYZ is tghe name of the function called by C++ functions.

    Third, a C function is not mangled. So when you call a C++ function from C you use the C++ function name and not the mangled name. Since these two name are never the same you can never call the C++ function using it's C name.

    Fourth, The trick: Tell the C++ compiler that the C++ function will be called from C and ot please turn off the name mangler. You lose function overloading in C++ for this function since all function names in C++ must be unique. That's why the mangler in the first place.

    To do this you use extern "C" in the C++ code:

    Code:
    extern "C" void MyFunction(int);
    in the header file and:
    Code:
    extern "C" void MyFunction(int)
    {
       //function body
    }
    Note that
    Code:
    extern "C"
    appears only in the C++ code.

    Fifth, Therefore any C function called by C++ must be extern "C" in C++. Likewise, any C function calling C++ functions must be extern "C" in C++.

    No changes are ever made to the C code.

    Comment

    • mac11
      Contributor
      • Apr 2007
      • 256

      #3
      As a follow up to weaknessforcats , there's a C++ faq section for mixing C and C++

      Comment

      Working...