Re: C/C++
Frederick Gotham wrote:
jacob navia posted:
You can use any C function in C++ by qualifying it as extern "C", and
that is it, you can use it as you want!
Not quite "any"; the function declaration must still be correct
C++ code, e.g. this is no good:
extern "C" int new(int delete);
and I think it mustn't have the same name as any overloaded C++
function in the same module (due to name mangling requirements).
Also, the function body must conform to a C ABI that the C++
compiler knows about.
Must every C++ compiler provide a facility for compiling C code?
No, but I don't know of any that don't.
Can the following program be considered universally portable?
/* stuff.c */
#include <stddef.h>
#include <stdlib.h>
char *AllocCharArray( size_t const len )
{
return malloc(len);
}
/* main.cpp */
#include <cstdlib>
extern "C" { char *AllocCharArray( std::size_t const len ); }
Note, the braces are unnecessary.
int main()
{
char * const p = AllocCharArray(64);
std::free(p);
}
I guess it is a semantic issue about the word "portable". If you're
happy for it to include "portable to systems with both a C++
compiler and a compatible C compiler" , then yes. Note that
there are other practical issues too; the two compilers must
also be configured to link gainst the same runtime library.