问题
The question says all the thing. I am using Qt Creator, which uses QMake and I want to build a .so
shared library file that has all its dependencies statically linked. Like libstdc++
, and etc.
But when I use CONFIG += static
it also changes the library to a static library and produces a .a
static file, which I don't want it. So my question is not a duplicate of this.
I searched here but I was not able to find any suitable thing.
回答1:
CONFIG += static
is the wrong flag, as stated by the documentation:
The target is a static library (lib only). The proper compiler flags will automatically be added to the project.
If you want to link dependencies statically, and produce a shared library, you need to pass a flag to the linker, so add QMAKE_LFLAGS += -static
to your .pro
file.
A simple tests results in a 16kb dll without that flag, and a 995kb dll with it. Also, if dependency walker is to be trusted, the larger dll has no external dependencies, while the smaller depend on libgcc
and libstdc++
(it is just a trivial std::cout
test).
So evidently, you don't really need a static qt or qmake build. Tested with the "stock" 32bit mingw version of Qt.
回答2:
You need three things:
- You need Qt itself built as a static library:
- You need said Qt statically linked to the runtime.
- You need to link your library statically to the runtime. This is handled automatically.
For all of it, you need to configure a custom Qt build with -static -static-runtime
arguments. Any executable/library you build using this Qt build will be statically linked to the runtime and statically linked to Qt (iff it uses Qt).
It is worth noting that none of the above requires any changes to your project's .pro
file. Conversely, there's nothing you can do to your project file to get the same effect, generally speaking. You have to get a properly configured Qt built, and everything will be handled from there.
There's no requirement on your library itself to use Qt, other than there being a project file that manages the build. For example, this would be a rudimentary library that doesn't use Qt nor C++:
TARGET = mylib
TEMPLATE = lib
CONFIG -= qt
SOURCES = mylib.c
HEADERS = mylib.h
As long as you invoke qmake
from a Qt configured as above, the shared library won't dynamically link to the language runtime (nor to Qt, but in this case it won't link to Qt at all!).
来源:https://stackoverflow.com/questions/40853899/how-to-have-static-linkage-in-a-shared-library-in-qt-creator