Rusty Lemur
Rusty Lemur

Reputation: 1875

How to statically link to a POCO C++ so file

In Linux I am trying to statically link a POCO C++ library so that I can distribute the resulting executable to other machines which don't have the POCO libraries installed. I can compile my source file (a simple gunzip replacement) like this:

$ g++ mygunzip.cpp  -L/usr/local/lib/ -lPocoFoundation

But the resulting executable requires that the PocoFoundation library is installed in the machine which executes it. I can't figure out how to statically link the PocoFoundation library so that the POCO library doesn't need to be installed on the target device. I've tried this and a couple other things, but nothing has worked:

$ g++ -o mygunzip.o mygunzip.cpp -static  /usr/local/lib/libPocoFoundation.so.60
/usr/bin/ld: attempted static link of dynamic object `/usr/local/lib/libPocoFoundation.so.60'
collect2: error: ld returned 1 exit status

I haven't delved in this kind of compilation before, so any guidance is appreciated.

Thanks

UPDATE I was able to get the static libraries built for POCO by running ./configure --static, make, sudo make install. Now I have the following static libraries:

$ sudo find /usr/local/lib/ -iname "*poco*a"
/usr/local/lib/libPocoJSON.a
/usr/local/lib/libPocoFoundationd.a
/usr/local/lib/libPocoUtild.a
/usr/local/lib/libPocoXMLd.a
/usr/local/lib/libPocoEncodingsd.a
/usr/local/lib/libPocoXML.a
/usr/local/lib/libPocoNet.a
/usr/local/lib/libPocoFoundation.a
/usr/local/lib/libPocoNetd.a
/usr/local/lib/libPocoJSONd.a
/usr/local/lib/libPocoEncodings.a
/usr/local/lib/libPocoUtil.a

But my compiled code still does not seem to be linked statically, since it is there is no difference when I add the -Bstatic flag.

$ g++ -o withoutStatic mygunzip.cpp  -L/usr/local/lib/ -lPocoFoundation
$ g++ -o withStatic mygunzip.cpp -Bstatic  -L/usr/local/lib/ -lPocoFoundation
$ g++ -o withStatic2 mygunzip.cpp -L/usr/local/lib/ -Bstatic -lPocoFoundation

$ md5sum with*
7b9374bb3f8772ed23db99090c269a84  withoutStatic
7b9374bb3f8772ed23db99090c269a84  withStatic
7b9374bb3f8772ed23db99090c269a84  withStatic2

ANSWER I think I found the solution: instead of -lPocoFoundation I used -l:libPocoFoundation.a. That resulted in a larger executable file, I'm assuming because it contains the static POCO library:

$ g++ -o withStatic3 mygunzip.cpp -L/usr/local/lib/ -l:libPocoFoundation.a

Upvotes: 1

Views: 2529

Answers (1)

SergeyA
SergeyA

Reputation: 62553

Unless you have a static (.a) library available, you can't link statically with it. .so files are not usable in static linking, they can only be used for dynamic linking.

Also, using -static as a command-line argument to gcc makes it link statically everything, including, for example, libstdc++, which is probably not what you want to do. If it is only Poco library you want linked statically, you need to supply linker flags -Bstatic and -Bdynamic around it.

Upvotes: 1

Related Questions