Can I use C and C++ objects in one program?

Johnny Favorite (it means "Reality Cop") allen@snakebite.com
Wed Dec 15 02:23:00 GMT 1999


dpace wrote:
> I am linking a .cpp piece of code with some .c files.
> But, I get a list of functions not found as though
> the .o files can't see each other's functions.

Welcome to the Wonderful World of Name Mangling.

In C++ you can have several functions that all have the same name but take
different parameters.  But it is a requirement that each function have a
UNIQUE name when it gets into the object file.  Hence, name mangling.  Each
C++ function's name will be "decorated" with funny characters describing its
parameters and return type and what class it belongs to when it hits the
object file.

C code knows nothing of this name mangling and so it will not be able to
call C++ functions.  In C++ there is sort of a workaround.  When you make a
declaration for a C function in a C++ header file, do it like this:

extern "C"
  {
    void functionName(int i);
  }

Then the C++ code will know that this name is NOT mangled and so it can call
it properly using the C calling convention.

That's kind of the hard way, though.  An easier way is to change the
extensions of all your .c files to .cpp, chances are excellent that they
will compile fine with few or no changes.  Then all your code will be
compiled according to the C++ rules, all functions will be name-mangled, and
all the code will get along fine.




More information about the Gcc-help mailing list