为每个动物图书馆创建一个单独的项目将是一种乏味且不切实际的方法。相反,最好将所有动物库包含在同一个项目中,并通过主项目/Qmake 文件管理它们。
为此,您可以为每个动物库创建一个单独的子目录,并将每个库的源文件放在其相应的子目录中。然后,使用 SUBDIRS 变量将子目录添加到主项目文件(.pro 文件)。
这是您的 .pro 文件的示例:
TEMPLATE = app
# List all the subdirectories for the animal libraries
SUBDIRS +=
dog
cat
bird
...
# Include any other necessary files and libraries
INCLUDEPATH += ...
LIBS += ...
# Specify any necessary build options
QMAKE_CXXFLAGS += ...
QMAKE_LFLAGS += ...
# Specify the output directory for the libraries
LIBS += -L$$PWD/libs
# Specify the names of the libraries to be built
dog.files = $$PWD/libs/libdog.so
cat.files = $$PWD/libs/libcat.so
bird.files = $$PWD/libs/libbird.so
...
使用这种方法,您可以通过运行 qmake 和 make 的单个命令构建所有动物库。生成的库文件将放置在指定的输出目录(例如 libs/)中,并且可以在运行时由您的主应用程序动态加载。
总的来说,这种方法允许您在单个项目文件中管理所有动物库,并使构建和分发应用程序变得更加容易。
更新:
如果每个动物类型库都是从单个 .cpp 文件创建的,则您不必为每个动物类型创建单独的目录。相反,您可以将所有动物 .cpp 文件放在一个目录中,然后使用 Qmake 通过为每个库指定 .cpp 文件的名称来构建每个动物类型库。
下面是一个示例,说明如何修改先前的 Qmake 文件以从单个 .cpp 文件构建每个动物类型库并使用通配符指定动物名称:
TEMPLATE = lib
CONFIG += shared
TARGET = AnimalLibs
# Get a list of all the .cpp files in the animal directory
ANIMAL_SOURCES = $$files(animals/*.cpp)
# Create a library for each animal .cpp file
for(FILE, ANIMAL_SOURCES) {
# Extract the name of the animal from the file name
ANIMAL = $$basename($$dirname(FILE))
# Create the library target for this animal
LIBNAME = lib$${ANIMAL}.so
$${ANIMAL}.target = $$LIBNAME
$${ANIMAL}.sources = $$FILE
# Add the library target to the list of targets
SUBDIRS += $$ANIMAL
}
# Build each animal type library
define_build_subdirs {
for(dir, SUBDIRS) {
message("Building $$dir")
SUBDIR = $$dir
include($$dir/$${SUBDIR}.pro)
}
}
# Link the libraries to the main project
LIBS += -L$$PWD -l$(ANIMAL) ...
在此示例中,ANIMAL_SOURCES 变量设置为 animals 目录中所有 .cpp 文件的列表。然后 for 循环遍历每个 .cpp 文件并为每种动物类型创建一个库目标。
ANIMAL 变量设置为从目录名称中提取的动物名称。 LIBNAME 变量设置为将要创建的库文件的名称,target 和sources 变量设置为特定于动物的目标。
最后,define_build_subdirs 函数用于构建每个动物类型库,并更新 LIBS 变量以将库链接到主项目。
使用这种方法,您可以通过简单地将新的 .cpp 文件添加到动物目录来添加新的动物类型,而无需修改 .pro 文件。新的动物类型将在构建项目时自动构建并链接到主项目