DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
C and C++ compilation system

Accessing C functions from C++

Because the C++ compiler encodes the parameter data type into the function name (see ``C++ external function name encoding''), the same function declaration in both a C and C++ program will refer to differently named functions in the object files. The following C and C++ modules can not be linked together as they are currently written.

callee.c:

   #include <stdio.h>
   

void subr (void) { printf("C subroutine\n"); }

caller.C:

   extern void subr (void);
   

main () { subr(); return 0; }

cc -c callee.c CC callee.o caller.C

Undefined first referenced symbol in file subr(void) caller.o ld: a.out: fatal error: Symbol referencing errors. No output written to a.out

The linker has reported an undefined function subr(void). In reality the C compiler has generated a function in callee.o by the name subr. The C++ compiler has generated a function reference to an external function which it expects to be named subr__Fv. To tell the C++ compiler that function subr() is an external C function and that all references to subr() should not reference an encoded function name, change the external function declaration in the C++ program to:
   extern "C" void subr(void);
The extern "C" notation can be stated on each external C function that a C++ program will reference. This can be quite cumbersome. Alternatively the external C function declarations can be grouped together and enclosed in this:
   extern "C" {
     .....
   }

The commonly used header files in /usr/include have been configured such that when included in a C++ compilation, the C function declarations are nested inside an extern "C" block. A C++ program, therefore, should have access to all the publically available functions in the various libraries that are part of the release.


Next topic: Quick-reference guide
Previous topic: C++ external function name encoding

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004