Hi!
I have some questions regarding calling C functions from C++ and vice
versa. This is based on some points I've found on parashift.com:
======================================================================
If you are including a C header file that isn't provided by the system,
you may need to wrap the #include line in an extern "C" { /*...*/ }
construct. This tells the C++ compiler that the functions declared in
the header file are C functions.
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.3
======================================================================
1. What if I don't wrap them? Is it possible to have runtime errors
because of that? I understand linker errors are possible.
2. When do you think this wrapping is not needed, i.e. what do you think
"provided by the system" was meant to mean? Parashift.com author gives
<cstdio> as an example, but what about POSIX headers like <pthread.h> or
<sys/socket.h>? Do you need to wrap them in extern "C" in portable code?
======================================================================
[32.6] How can I create a C++ function f(int,char,float) that is
callable by my C code?
The C++ compiler must know that f(int,char,float) is to be called by a C
compiler using the extern "C" construct [...]
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.6
======================================================================
======================================================================
[...] static member functions do not require an actual object to be
invoked, so pointers-to-static-member-functions are usually
type-compatible with regular pointers-to-functions. However, although it
probably works on most compilers, it actually would have to be an extern
"C" non-member function to be correct, since "C linkage" doesn't only
cover things like name mangling, but also calling conventions, which
might be different between C and C++.
http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2
======================================================================
3. Is it possible to have runtime errors if you don't use extern "C" in
this case? I think YES?
4. What effect does extern "C" have on C++ function in this case? It's
about generating machine code of the function itself, right? No wrapper?
So when you call this C++ function from within C++ code (from the same
or another translation unit), the C calling convention should be used?
I am doing some initialization using pthread_once, and apparently it
works here on Debian GNU/Linux with g++ when I pass a private static
member function pointer to pthread_once (no extern "C", either). :-)
I only care about POSIX and GNU/Linux.
STF
http://eisenbits.homelinux.net/~stf/
OpenPGP: DFD9 0146 3794 9CF6 17EA D63F DBF5 8AA8 3B31 FE8A
[Non-text portions of this message have been removed]