gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Is it possible to embed a c source code in c++

#46197 - bmnb1234 - Tue Jun 21, 2005 5:34 pm

Hi I got a question I am writing a game in c++, I presently found a sound source code but it is in c. Is it possible to embed a c source code in c++ or do I have to rewrite it in c++?

Thank you for your time!
Jason

#46200 - poslundc - Tue Jun 21, 2005 5:40 pm

Since C++ is a superset of C, all C code runs in C++.

In practice, a small percentage of the code may require some tweaking. Feel free to post if you have any difficulties getting the code to work.

Dan.

#46201 - DekuTree64 - Tue Jun 21, 2005 5:44 pm

You'll need to wrap any global functin prototypes in the .h like this:

Code:
#ifdef __cplusplus
extern "C" {
#endif

extern void DoStuff();
extern void DoOtherStuff();

#ifdef __cplusplus
}
#endif


That's because the .c file will compile with the global symbols exactly as they appear. C++ uses name mangling to support argument overloading, so it will try to mangle the names according to the arguments when calling functions too.
extern "C" tells it to call those functions with their names as they are.
_________________
___________
The best optimization is to do nothing at all.
Therefore a fully optimized program doesn't exist.
-Deku

#46215 - sajiimori - Tue Jun 21, 2005 7:24 pm

Usually you don't have to declare things extern "C" unless the code was already compiled without name mangling. If you've got the source, then you can compile it as C++ and then the names will be mangled along with everything else.