LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   Mixing Cpp and C (http://www.linuxquestions.org/questions/linux-software-2/mixing-cpp-and-c-4175419471/)

cmccullo 07-30-2012 10:39 PM

Mixing Cpp and C
 
I am trying to compile a program with three parts main.c, file1.c, and file2.cpp. Main.c and file1.c use MIT Kerberos, krb5, functions but no cpp statements. File2.cpp uses MPIR classes so I need to use the g++ compiler. I don't know if these libraries are important, but I include them for thoroughness.

If I compile and link everything with g++, I get a link error 'undefined reference to krb5_read_message' which is in both main.c and file1.c. I even tried changing the file extensions of main and file1 to cpp - no change.

If I compile main.c and file1.c with gcc, and compile file2.cpp with g++, then link with g++, I get a link error 'undefined reference to MyFunction' which is in file2.cpp.

I don't know if the krb5 build is compiled with gcc or g++, but would it help to force the krb5 build to use the g++ compiler? If so, how do I do that?

business_kid 07-31-2012 03:57 AM

I'm sure you can grok someone else's makefile for ideas
One way might be to set it up in the Makefile as 2 targets, or 2 directories.

target1:
CC=g++
<stuff>

target2:
CC=gcc
<stuff>

install:
Linking here
<stuff>

Then run make target1; make target2; make install

jmajor 08-06-2012 10:02 PM

The object files between C and C++ use different name mangling. C prepends an underscore, whereas C++ mangles in some argument type info.

To call C from C++ you need to put your your C function declarations (in the header included by C++) inside of an 'extern "C" { .... }' block.

Calling C++ from C is more problematic as the C++ class initialisations for globals may not get called properly without some work. The overloading of functions for differing argument types is likely to upset your poor old C compiler somewhat.

Should be possible for you to write a C++ main() and rename and wrap you C main(). You'll need to do some work to ensure that C is called from C++ and not the other way around.

See http://en.wikipedia.org/wiki/Compati..._C_and_C%2B%2B

cmccullo 08-16-2012 05:17 PM

I have no idea what grok is. I tried business_kid's suggestion as best I could understand it and it did not work. Make said target1 was already up to date, or something like that.

Jmajor's suggestion seems very complicated. Thanks, but I'm not trying to make a library.

What I found works is to either change the file extensions from .c to .cpp, or add the compiler option -xc++. Then compile everything with g++.


All times are GMT -5. The time now is 05:35 PM.