Using a static library in Qt Creator

2019-01-13 00:41发布

问题:

I'm having a hell of a time finding documentation which clearly explains how to use a static library in Qt Creator.

I've created and compiled my static library using Qt Creator (New=>Projects\C++ Library=>Set type to "Statically Linked Library"). It compiles and spits out a ".a file".

The problem I encounter is when I try to use the library. I have another project that would like to use it (#include files in the library, etc) but I don't know the proper way to link with the library or include files from the library.

回答1:

LIBS += -L[path to lib] -l[name of lib]

Note! that filename of lib: lib[nameOfLib].a and you have to pass only original part -l[nameOfLib]



回答2:

In your project that uses the library make the LIBS variable point to your lib's path.
To include files from the library, add the library folder to the INCLUDEPATH and then do a regular #include in your code files.

e.g:

# the binary's .pro  
LIBS += c:/mylibs/math.lib
INCLUDEPATH += c:/mylibs

Edited:
-L tells qmake that the path is a directory that it can search for libraries -l tells it that the path is a file, but take note of the observation below.

From the qmake docs:

This variable contains a list of libraries to be linked into the project. You can use the Unix -l (library) and -L (library path) flags and qmake will do the correct thing with these libraries on Windows (namely this means passing the full path of the library to the linker). The only limitation to this is the library must exist, for qmake to find which directory a -l lib lives in.

Note: On Windows, specifying libraries with the -l option, as in the above example, will cause the library with the highest version number to be used; for example, libmath2.lib could potentially be used instead of libmathlib. To avoid this ambiguity, we recommend that you explicitly specify the library to be used by including the .lib file name suffix.



回答3:

..from QT project creator

  1. goto projectName.pro from left hand side menu
  2. type LIBS +=
  3. rightClick AddLibrary


回答4:

The variant

 LIBS += -L[PATH_TO_LIB_DIR] -l[LIBNAME] 

doesn't work if you have both static libLIBNAME.a and dynamic libLIBNAME.so libs in the same folder PATH_TO_LIB_DIR.
In this case on my linux with QMake v 3.0 the dynamic one is linked by default.
To force linkage with static one you need to specify it explicitly without any options.

LIBS += PATH_TO_LIB_DIR/libLIBNAME.a


回答5:

Is it

LIBS += -L"/some path" -l"somename.a"

or

LIBS += -L/somepath -lsomename.a

or

LIBS += -L/somepath -lsomename"

This should be as easy as it gets but for some reason it is EXTREMELY hard to pull up a search result for because there are so many hits of forums of people asking for help and I've followed every tip I can get but no help...