c++ - 使文件夹中的所有文件可被所有项目(子目录)访问

标签 c++ cmake linker

我的存储库中有多个项目(子目录)。所有项目都只有一个名为main.cpp的可执行文件,并且它们都使用common语句中的#include文件夹中的库。文件夹结构如下所示:

root
|
├────common
|    ├──── example.h
|    ├──── example.cpp
|    ├──── *.h          # many header files
|    └──── *.cpp        # many source files
|
├────Project_A
|    ├──── CMakeLists.txt
|    └──── main.cpp
|
├────Project_B
|    ├──── CMakeLists.txt
|    └──── main.cpp
|
└──── CMakeLists.txt
这是我尝试写根目录的CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
project ("root")

file(GLOB_RECURSE CommonLibs ${CMAKE_SOURCE_DIR}/common/*.cpp)
link_libraries(${CommonLibs})

add_subdirectory ("Project_A")
add_subdirectory ("Project_B")
Project_A的CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
add_executable (Project_A "main.cpp")
Project_B的CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
add_executable (Project_B "main.cpp")
但是,在运行任何项目时,都会出现此错误:
LNK1107 invalid or corrupt file: cannot read at 0x7AC, file example.h
我不认为该文件已损坏,因为在尝试在根目录的CMakeLists.txt中使用link_libraries()之前,我遇到了其他错误:
Unresolved external symbol SomeNamespace::ExampleClass::ExampleClass(bool)
可能重复
其他问题,例如this one不能解决我的问题,因为它们通常使用更复杂的文件夹结构。还有一些问题试图仅针对单个项目,例如this one,但我有多个项目。
您能提供一个简洁的解决方案吗?

最佳答案

在您的CMakeLists.txt目录中添加一个common/:

root
|
├────common
|    ├──── CMakeLists.txt <-------- Add this
|    ├──── example.h
....
common / CMakeLists.txt
file(GLOB_RECURSE CommonLibsFiles ${CMAKE_CURRENT_SRC_DIR}/*.cpp)
add_library(CommonLibs ${CommonLibsFiles})
...
根的CMakeLists.txt
...

### NO NEED FOR THESE
file(GLOB_RECURSE CommonLibs ${CMAKE_SOURCE_DIR}/common/*.cpp)
link_libraries(${CommonLibs})
###

add_subdirectory(common) #CommonLibs will now be visible to children directories
...
现在根据需要链接库。例如对于项目A:
Project_A的CMakeLists.txt
cmake_minimum_required (VERSION 3.8)
add_executable (Project_A "main.cpp")
target_link_libraries(Project_A PRIVATE CommonLibs) #link to common libs here,
所有创建的目标/变量或对父cmake文件可见的目标/变量对 child 均可见。相反,事实并非如此。为了让 child 将变量展示给 parent ,他们需要明确指定PARENT_SCOPE

关于c++ - 使文件夹中的所有文件可被所有项目(子目录)访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62599941/

相关文章:

c++ - 计算3D中线和点之间的角度

ubuntu - 在 wsl 上安装 doxygen 无法找到 Iconv(缺少 : ICONV_COMPILES)

c++ - 无法构建cpprestsdk

visual-studio - 如何在项目上同时支持 vcxproj 和 cmake?

java - g++、ld 和 JNI - 链接问题

c++ - 动态链接

c++ - C++ 中的属性

C++从模板参数类型生成包含开关/映射的函数体

c++ - this-> 引用所有内容

c - 在 GNU/Linux 上链接插件时如何巧妙地检测 undefined symbol ?