1

I am trying to statically link a C++ library to a C project but can't seem to figure a way out. I read multiple posts but nothing helped. Below is the snippet of my Makefile:

 CFLAGS += -I../path/to/headers
 LIBS += ../path/to/lib.a

I get the below linking error:

"undefined reference to ...
collect2: ld returned 1 exit status"

I checked this post for ordering but I don't that is an issue here: c++ undefined references with static library

I wanted to know if it is even possible. If so, what flags I would need to add into my C project Makefile.

pree
  • 2,297
  • 6
  • 37
  • 55
  • 3
    you cannot direct link c++ into c, since the names would under name mangling. you can use `extern "C"` (or guess the mangled name :P ) – apple apple Oct 09 '18 at 04:36
  • 1
    In addition to @appleapple Guessing the mangled name is not that complicated. Once, code is compiled you may have a look into the object or library files (e.g. with `nm` on Linux). To bad that the name mangling is not standardized and depends on compiler/platform. I'm with appleapple for his/her better advice about `extern "C"`. Though, it has limitations as well as the marked variables and functions really must conform to C. (IMHO, for the latter fact there is no way out.) – Scheff's Cat Oct 09 '18 at 05:36
  • And, is it applicable to both static and dynamic (using SO file instead of static) linking? – pree Oct 09 '18 at 14:43
  • Could you show which references are unresolved? Are they expected to come from that C++ library? – Alex Cohn Oct 09 '18 at 14:59
  • These references are from my C++ library that I'm trying to integrate. In the above example, it's just an function call. E.g. undefined reference to 'call_add', where call_add is a function declared in a header and implementation in some C++ file. – pree Oct 09 '18 at 16:11

1 Answers1

0

If the library that you pretend to link with is not prepared to export C compatible function names in the object code, you should add a C++/C bridge to your project.

This bridge may consist of a C++ header and source files where you write C++ code that uses the C++ library where the symbols that you need to use from your C program are exported in a C compatible way.

You should do something like this:

bridge.h

#include <cpplibrary.h>
#ifdef __cplusplus
extern "C" {
#endif

int bridge();

#ifdef __cplusplus
}
#endif

bridge.cpp

#include "bridge.h"

extern "C" {
int bridge() {
CppLibrary *object = new CppLibrary();
return object->returnInt();
}

} // extern "C"

This C++ code is compiled exporting names that the C linker can understand, allowing to indirectly use the C++ code of that given library.

UaT
  • 116
  • 9