Issue
I have a C++ project and I want to compile it into a single binary file which contains all the shared libraries, third-parties, and so on. I want to move the compiled file into different servers without installing any dependencies. That's why I need an all-in-one/bundled binary file.
For example, I've tried to compile this:
g++ sample.cpp -o sample -Wl,-Bstatic -l:libyaml-cpp.so
But I got this error, while I really have libyaml-cpp.so
file in the /usr/lib
directory:
/usr/bin/ld: attempted static link of dynamic object `/usr/lib/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../lib/libyaml-cpp.so'
collect2: error: ld returned 1 exit status
What's the best way to fix the issue and generally have a compiled file with all dependencies in GNU/Linux platform?
Solution
Normally you would use g++ sample.cpp -o sample -static -lyaml-cpp
.
But it seems Arch tends to not include static libraries in their packages. Your options are:
Build yaml-cpp yourself to get a static library.
Distribute the dynamic library along with your executable.
To avoid having to install it in system directories, you'll can do one of:
Set
LD_LIBRARY_PATH
env variable when running your program, to the location of the.so
.Add
-Wl,-rpath='$ORIGIN'
to the linker flags, then the resulting binary will automatically try to load libraries from its directory, before checking system directories.You can also modify rpath in existing executables and shared libraries using
patchelf
. This is useful when you want to include shared libraries that other shared libraries depend on, and the latter weren't compiled with-Wl,-rpath='$ORIGIN'
.
Answered By - HolyBlackCat