1

I have a static library with C++ internals but with a C wrapper so that C code can call the library.

  • Using g++, no issue.
  • Using gcc, I get lots of undefined reference to at the library's internal functions.
  • The C code calls only the C functions in the C wrapper.
  • The problem is from internal calls inside the library not to the "API".

The C wrapper contains:

#ifdef __cplusplus
extern "C" {
#endif

Why? Can we link a static library containing C++ but exposing only C functions to a C application?

What's the point of writing a C wrapper for a C++ library if we still need to compile the C code as C++?

Alexis
  • 2,136
  • 2
  • 19
  • 47
  • 1
    It's not so much a matter of C vs C++ as it is about dependencies. The library is written in C++, and sounds like it uses the C++ runtime. g++ links it implicitly, which is why it "just works". – StoryTeller - Unslander Monica Dec 21 '21 at 11:40
  • Please show a [mre] including the full error messages – Alan Birtles Dec 21 '21 at 11:42
  • @StoryTeller-UnslanderMonica But why? The library is already compiled. The C app communicates with the library only via C calls. The linker shouldn't care what the library actually contains internally, what matters is what the C app calls. No? – Alexis Dec 21 '21 at 14:05
  • 1
    The duplicate is far too broad to be helpful. Voting to re-open. – Lundin Dec 21 '21 at 14:16
  • @Alexis No need to edit your question if it gets closed, that's just confusing. Instead explain in comments why it isn't a duplicate. I've gold badger re-opened the question now, you can remove those edits. – Lundin Dec 21 '21 at 14:18
  • Thank you @Lundin, it's removed. In the meantime I found the solution that worked: https://stackoverflow.com/questions/18195932/create-a-c-wrapper-around-a-c-library-that-can-be-linked-by-a-c-linker I'll delete the question in few minutes since it's still a duplicate. – Alexis Dec 21 '21 at 14:19
  • 1
    No need to delete the question but we can pick that one you found as target instead. – Lundin Dec 21 '21 at 14:20
  • Sure, thank you! – Alexis Dec 21 '21 at 14:21
  • 1
    *"The linker shouldn't care what the library actually contains internally"* - For an archived library, it very much does care. A library for static linking is essentially just a bunch of object files wrapped in an archive. Whatever those objects call need to be brought in for the linker to resolve. The C++ runtime is just one case of that. You'd hit the same problem if you depend on 3rd-party library code too. – StoryTeller - Unslander Monica Dec 21 '21 at 14:27
  • @StoryTeller-UnslanderMonica It makes sense but it just defeats the purpose of writing a C-wrapper... I hope it doesn't create issues with `cgo` or `rust`. – Alexis Dec 21 '21 at 14:48

0 Answers0