I tried to link a static library (compiled with gcc) to a c++ program and I got \'undefined reference\'. I used gcc and g++ version 4.6.3 on a ubuntu 12.04 server machine. F
While the accepted answer is absolutely correct, I thought I'd just add an observation. Some editors have trouble with the open / close brace, and will indent the entire extern "C"
scope in the header. If mylib.h
is a key header for a library, you might consider:
#if defined (__cplusplus)
#define _MYLIB_INIT_DECL extern "C" {
#define _MYLIB_FINI_DECL }
#else
#define _MYLIB_INIT_DECL
#define _MYLIB_FINI_DECL
#endif
All other headers in mylib
library, e.g., mylib_aux.h
, can be of the form:
#ifndef _MYLIB_AUX_H
#define _MYLIB_AUX_H
#include
_MYLIB_INIT_DECL
... header content ...
_MYLIB_FINI_DECL
#endif /* _MYLIB_AUX_H */
Obviously, the names I'm using are arbitrary, but for multiple library headers, this approach has been useful to me.