Friday, March 28, 2008

cross linking problem with g++ and gcc

The names of C++ functions are "mangled" to include information about
the types of the the function's arguments. To use C functions from C++
source or vice versa, they must be declared extern "C". You can group
these with extern "C" { ... }

If you look at the standard header files, you will see things like

#ifdef __cplusplus
extern "C" {
#endif

[declarations of C functions]

#ifdef __cplusplus
}
#endif


or, more cleanly, define in some common header file

#ifdef __cplusplus
#define BEGIN_C_DECLS extern "C" {
#define END_C_DECLS }
#else
#define BEGIN_C_DECLS
#define END_C_DECLS
#endif

and then

BEGIN_C_DECLS

[declarations of C functions]

END_C_DECLS


You should follow a similar strategy in the header files
for your project. Make sure that every global function
is declared in one of those header files, and that the
appropriate header files are included. Every function which
is defined or used in C code must be declared extern "C".
Try not to do so for functions that are only used in C++ code,
since that will lose type-safe checks, but it should otherwise be
harmless. As long as every global function is declared in a header
file and each header file is always included in every file that uses
any functions from it, the link should succeed. (These are basic
principles of C/C++ engineering, regardless of whether you are
merging the two).

No comments: