gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:48:35 27 4
gpt4 key购买 nike

我的存储库中有多个项目(子目录)。所有项目都只有一个名为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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com