g++ linking to gcc compiled libraries

Brian Dessent brian@dessent.net
Wed Oct 3 18:00:00 GMT 2007


"Frederich, Eric P21322" wrote:

> If I compile both the library and program using g++ it works fine, but
> then I can't link to the c library from c programs.
> 
> Here is the output of me trying to use g++ to link to a c library
> compiled with gcc.

Your 'cfun' was not declared 'extern "C"' which means when the
clibrary.h header is parsed as C++, the function is treated as C++ with
all that entails.  Note the error message:

> cppsource.o(.text+0x83): In function `main':
> : undefined reference to `cfun(int)'

It's complaining about not being able to find 'cfun(int)'.  If this were
C, it would have just said 'cfun' because C functions are not
decorated/mangled, but since the header was parsed as C++, the code is
calling the C++ version of the function with a mangled name that encodes
its type.

If you want your C header to be usable in C++ code you must wrap it with

#ifdef __cplusplus
extern "C" {
#endif

...

#ifdef __cplusplus
}
#endif

This is not gcc specific at all.

Brian



More information about the Gcc-help mailing list