cmake:对对象库的依赖 [英] cmake: dependencies on object libraries
问题描述
假定以下目录结构:
CMakeLists.txt
libA
contents: a.cpp
a.h
src
contents: hello.cpp
target1.cpp
target2.cpp
include
- contents: hello.h
我有一个静态库 A ,用于项目的主要源代码。
I have a static library A, used within the main source code of the project.
尝试1 :
. . .
add_executable(t1 src/target1.cpp src/hello.cpp)
add_dependancies(libA)
target_include_directories(t1 PRIVATE ${PROJECT_SOURCE_DIR}/include
target_link_libraries(t1 PRIVATE /path/to/libA)
. . .
此功能适用于 t1
,但是,如果要编译 target2.cpp
,则需要重复此过程,因此 hello.o
生成两次。
This works for t1
, however, if I want to compile target2.cpp
I would need to repeat this process, hence hello.o
is generated twice.
尝试2 :
我正在考虑更改此方法以生成一个 hello.cpp
的对象库,只是将对象库添加到目标中,但是,由于找不到库 A <中定义的标头,我遇到了编译问题/ em>,因为首先编译了对象库,并且尚未将头文件复制到 CMakeFiles
。
Attempt 2:
I was thinking to change this approach to generate an object library for hello.cpp
, and simply add the object library to the targets. Yet, I get compilation problems as it cannot find the headers defined in library A as the object library is compiled first and the heade files are not yet copied to the CMakeFiles
.
. . .
add_library(libA src/hello.cpp)
add_executable(t1 src/target1.cpp $<TARGET_OBJECTS:libA>)
add_dependancies(libA)
target_include_directories(t1 PRIVATE ${PROJECT_SOURCE_DIR}/include
target_link_libraries(t1 PRIVATE /path/to/libA)
. . .
是否可以定义依赖项,因此静态库 A
Is there a way to define a dependancy, so that the static library A is compiled before?
推荐答案
在注释中,您提到了 libA $ c实际上,使用
ExternalProject_Add
将$ c>带入构建系统。这意味着您在同一个 CMakeLists.txt
中混合了常规项目和外部项目,因此强烈建议不要这样做。
In the comments, you've mentioned that libA
is actually brought into the buildsystem using ExternalProject_Add
. Which means that you're mixing "normal" and external projects in the same CMakeLists.txt
, and that's highly discouraged.
使用ExternalProject的首选方法是所谓的Superbuild方法:将 all 项目视为外部项目,并使用 ExternalProject_Add
将其添加,包括您自己的项目。这样,主CMakeList就变成了超级构建—。子项目的容器和驱动程序。在此级别上,您可以根据需要在各个项目之间引入依赖关系。
The preferred way of working with ExternalProject is the so-called Superbuild approach: treat all the projects as external and add them with ExternalProject_Add
, including your own project. That way, the master CMakeList becomes just the superbuild — a container and driver for subprojects. At this level, you can introduce dependencies between the individual projects as necessary.
配置并构建一次超级构建,以正确设置所有项目。然后,将其降低一级,就好像您的项目是独立的一样;所有依赖项都已经准备好了。
Configure and build the superbuild once to get all projects set up correctly. After that, go one level lower and work on your project as if it was standalone; all dependencies will have been already prepared and ready.
这篇关于cmake:对对象库的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!