CBFalconer said:
They are not compiled with the C++ compiler, they should be
compiled with the C compiler. ...
The purpose of the exercise was to find out how to call code compiled by
C++ from code compiled in C. How would compiling them with C serve that
purpose?
... The object code may be linked with
the C++ linker. The <extern "C"> term is only in the .h file that
describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.
Remember, the languages are different.
Yes, they are different languages - so what?. C++ defines features that
allow C++ code to call C code, and to define C++ functions that can be
called from C.
The program below contains a function named bar() compiled by C++ with
"C" language linkage. I know from previous discussions with you that you
have said some confusing things about whether you consider such a
function to be a C function or a C++ function.
Rather than repeat my previous failed attempts to get a straight answer
out of you about that question, I've written a program that contains one
function named foo() which is compiled in C, and is therefore
unambiguously a C function. It contains another function named baz()
compiled in C++ that has "C++" language linkage, so it is unambiguously
a C++ function. foo() calls bar() which calls baz(). Therefore, no
matter how you classify bar(), this program contains a C function
calling a C++ function.
foobar.h:
========================
#ifndef FOOBAR_H
#define FOOBAR_H
#ifdef __cplusplus
extern "C" {
#endif
void foo(int);
void bar(int);
#ifdef __cplusplus
}
#endif
#endif
foo.c:
===================================
#include <stdio.h>
#include "foobar.h"
void foo(int i) {
puts("About to call bar()");
bar(i);
puts("Finished calling bar()");
}
main.C
==================================================
#include <iostream>
#include "foobar.h"
int main()
{
foo(42);
}
static void baz(int i)
{
std::cout << "the number is:" << i << std::endl;
}
void bar(int i)
{
baz(i);
}
I built the complete program as follows:
~/testprog/CfromC++(63) gcc $CFLAGS -c foo.c
In file included from foo.c:2:
~/testprog/CfromC++(64) !g++
g++ $CXXFLAGS main.C foo.o -o foobar
~/testprog/CfromC++(65) printenv CFLAGS
-std=c99 -pedantic -Wall -Wpointer-arith -Wcast-align -Wwrite-strings
-Wstrict-prototypes -Wmissing-prototypes
~/testprog/CfromC++(66) printenv CXXFLAGS
-std=c++98 -pedantic -Wall -Wpointer-arith -Wcast-align
-fno-enforce-eh-specs -ffor-scope -fno-gnu-keywords
-fno-nonansi-builtins -Wctor-dtor-privacy -Wnon-virtual-dtor
-Wold-style-cast -Woverloaded-virtual -Wsign-promo
~/testprog/CfromC++(67) foobar
About to call bar()
the number is:42
Finished calling bar()
If, as you say, C cannot access C++ code, then what exactly is the above
program doing when foo() calls bar() which calls baz()?