C++ 如何使用 Qt 构建静态库和可执行文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10034825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:31:33  来源:igfitidea点击:

How do I build a static library and executable with Qt?

c++qtqmake

提问by chacham15

To simplify the situation, lets say that there are 2 files: core.cppand main.cpp.

为了简化情况,假设有 2 个文件:core.cppmain.cpp.

core.cppcontains the functionality of the program and main.cppcontains the basic main()implementation.

core.cpp包含程序的功能和main.cpp基本main()实现。

I want Qt (using qmake and the .pro files) to

我想要 Qt(使用 qmake 和 .pro 文件)

  • first build core.aand then
  • use that and main.cppto build main.exe.
  • 首先构建core.a然后
  • 使用它并main.cpp构建main.exe.

How do I set this up in the qmake file?

如何在 qmake 文件中进行设置?

回答by Masci

Filesystem layout:

文件系统布局:

MyProject
|_ myproject.pro
|_ core
   |_ core.cpp
   |_ core.h
   |_ core.pro
|_ app
   |_ main.cpp
   |_ app.pro

myproject.pro:

myproject.pro:

TEMPLATE = subdirs
CONFIG += ordered
SUBDIRS = core \
          app
app.depends = core

core.pro:

核心.pro:

TEMPLATE = lib
CONFIG += staticlib
HEADERS = core.h
SOURCES = core.cpp

app.pro:

app.pro:

TEMPLATE = app
SOURCES = main.cpp
LIBS += -L../core -lcore
TARGET = ../app-exe # move executable one dire up

回答by Farabi Ahmed Tarhan

If you are utilizing resources in your static library you should import them in your application as well. Q_INIT_RESOURCEis the way of importing a resource file into the application.

如果您正在使用静态库中的资源,您也应该将它们导入到您的应用程序中。Q_INIT_RESOURCE是将资源文件导入应用程序的方式。

Assume that you have a resources file with file name as myResources.qrcin static library. Then, you should initialize this in the app as given below:

假设您有一个资源文件,文件名与myResources.qrc静态库中的一样。然后,您应该在应用程序中初始化它,如下所示:

QApplication a(argc, argv);

Q_INIT_RESOURCE(resources); //Magic is here.

MainWindow w;
w.show();
a.exec();

The .pro file might be modified as given below for the great example given by Masci:

对于 Masci 给出的例子,.pro 文件可能会被修改如下:

TEMPLATE = lib
CONFIG += staticlib
HEADERS = core.h
SOURCES = core.cpp
RESOURCES += myResources.qrc