What is the easiest way to reference libraries in Qt projects?
-
03-10-2019 - |
Question
I have two Qt4 Gui Application projects and one shared library project, all referenced under a .pro file with the "subdirs" template. So, it's like:
- exampleapp.pro
- app1.pro
- app2.pro
- sharedlib.pro
Now, what I want to do is reference sharedlib from app1 and app2 so that every time I run app1.exe, I don't have to manually copy sharedlib.dll from its own folder to app1.exe's folder.
I could set PATH environment variable in the projects window, but this isn't very portable. I've looked at putting the LIBS variable in the app1.pro file, but I'm not sure if that refers to statically linked libraries only - I've tried it with various syntaxes and it doesn't seem to work with shared libs.
Solution
You can organize your project as follows:
- Project1
- bin
- lib
- app1
- app2.pro
- app2
- app2.pro
- sharedlib
- sharedlib.pro
in sharedlib.pro can add something like this:
TEMPLATE = lib
TARGET = sharedlibr
QT + = core \
gui
DESTDIR = .. / lib
DESTDIR: guarantees that the result of the compilation will be copied to the location ".. / lib"
as for applications app1 and app2:
TEMPLATE = app
TARGET = app1
QT + = core \
gui
DESTDIR = .. / bin
this only for development, when creating the installer, the libraries and executables are placed in the appropriate dirs, depending of the operating system.
OTHER TIPS
To add to this (a bit late!), one can use QMAKE_POST_LINK
to copy files around after a build has been completed. Example:
defineReplace(formatpath) {
path = $$1
win32 {
return(\"$$replace(path, "/", "\\")\")
} else:unix {
return($$replace(path, " ", "\\ "))
} else {
error("Unknown platform in formatpath!")
}
}
win32:COPY_CMD = copy
unix:COPY_CMD = cp -P
macx:COPY_CMD = cp -R
win32:CMD_SEP = $$escape_expand(\n\t)
unix:CMD_SEP = ";"
win32:LIB_EXT = dll
unix:LIB_EXT = so*
macx:LIB_EXT = dylib
# Put here the directory of your library's build dir, relative to the current directory
# A path is given for example...
MYLIB_BUILD_DIR = $$_PRO_FILE_PWD_/../lib/bin
QMAKE_POST_LINK += $$COPY_CMD $$formatpath($$MYLIB_BUILD_DIR/*.$$LIB_EXT) $$formatpath($$OUT_PWD/$$DESTDIR) $$CMD_SEP