Re: c++ calling c functions



CBFalconer <cbfalconer@xxxxxxxxx> writes:
Keith Thompson wrote:
CBFalconer <cbfalconer@xxxxxxxxx> writes:
[...]

No, you can't link C++ to C, in general.

I don't believe that's correct. Further information would be
topical in comp.lang.c++, not in comp.lang.c (since it's C++, not
C, that defines the mechanisms), but see questions 32.5 and 32.6
in the "C++ FAQ Lite" at <http://www.parashift.com/c++-faq-lite/>.

The point is that C++ function names are modified, to express the
parameter types, in the linkable object code sections. C does not
do this, since it doesn't have shared function names etc. Thus the
C++ code can be told (with the "extern C {...}") that selected C
functions are to be accessed (from C++) with unmodified names. The
reverse is not possible.

Thus I gave the general method for making C object code available
to aa C++ program.

Maybe we are confusing the direction of linking? You can call C
from C++, but not C++ from C (without impossible diddling).

No, I'm asserting that it's possible to call C from C++ *and* to call
C++ from C.

The C++ FAQ agrees, and directly contradicts your claim. Its authors
certainly know C++ better than I do.

Furthermore, I've just done it. Here are my source files:

==> func.h <==
#ifdef __cplusplus
extern "C" {
#endif
void func(int i, char c, float x);
#ifdef __cplusplus
}
#endif

==> func.C <==
#include "func.h"
#include <iostream>
void func(int i, char c, float x)
{
std::cout << "In func, sizeof 'a' = " << sizeof 'a' << "\n";
std::cout << "i = " << i << ", c = '" << c << "', x = " << x << "\n";
}

==> c_main.c <==
#include "func.h"
#include <stdio.h>
int main(void)
{
printf("In C main, sizeof 'a' = %d\n", (int)sizeof 'a');
func(42, '$', 123.456);
return 0;
}

==> cpp_main.C <==
#include "func.h"
#include <iostream>
int main()
{
std::cout << "In C++ main, sizeof 'a' = " << sizeof 'a' << "\n";
func(42, '$', 123.456);
return 0;
}

Here's the output of the C main program:

In C main, sizeof 'a' = 4
In func, sizeof 'a' = 1
i = 42, c = '$', x = 123.456

Here's the output of the C++ main program:

In C++ main, sizeof 'a' = 1
In func, sizeof 'a' = 1
i = 42, c = '$', x = 123.456

<OT>Both main programs had to be linked with "g++", because both need
the C++ standard library.</OT>

But as you can see the C program was compiled as C and successfully
called a C++ function.

Obviously this requires some compatibility between the C and C++
implementations.

--
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.