Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a library written in C++ from a pure C project on Linux?

Found this statement over at PSE: (quoting Bob)

One of my favorite tricks on Windows and Mac OS doesn't work on Linux. That trick is to write a DLL/dylib using C++ internals, export a C API, and then be able to call into it from C programs. Linux shared objects (the local equivalent of a DLL) can't really do that easily, because the C++ standard library .so isn't in the default search path. If you don't do a bunch of weird stuff to your C program, it will fail as soon as it dynamically loads your .so at runtime: your .so will try to dynamically load the standard library .so, it won't find it, and then your program will exit.

I find that a bit odd. How accurate is this, factoring in possible differences between the major desktop/server distros of Linux?

This is purely out of curiosity, as I do Windows only (C++) programming at the moment.


As for Windows, I had to do a bit of lookup and I'll put it here for reference: A C++ executable will normally link to MSVCR*.DLL for the C std library and MSVCP*.DLL for the stuff of the STL that resides in this DLL. Both of these either reside in the system32 directory, or, for the manifested stuff they'll reside in a subdir of Windows SideBySide cache (winsxs folder).

like image 530
Martin Ba Avatar asked Oct 10 '22 21:10

Martin Ba


1 Answers

I am doing this thing all the time, and it works fine. I am pretty sure that that guy had a totally unrelated problem and blamed the library search paths for it.

I have never seen any linux distro where the libstdc++.so is not in the /usr/lib[64]/ path.

Which also makes me wonder how C++ programs generally work for that guy, since to my knowledge the search path for .so files is language agnostic.

Maybe he always uses a special version and compiles all his programs with -rpath linker options? But even then, just adding that option to his C programs would work too.

it will fail as soon as it dynamically loads your .so at runtime: your .so will try to dynamically load the standard library .so, it won't find it, and then your program will exit.

This makes me wonder if he solely refers to using dlopen() on your own .so. But also then it works just fine, unless you did not link the .so to your libstdc++.so (which would then be your own fault; it would be the same problem had you dependencies on any other library, regardless what language it was written in).

like image 81
PlasmaHH Avatar answered Oct 13 '22 18:10

PlasmaHH