如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP
how to make cmakelists.txt compile cpp that uses functions and classes declared and implemented in some other place
我在 2 个头文件中定义了一些函数类,并在某个文件夹的 cpp 文件中实现。我将它们用于位于同一目录中的一些 cpp 程序(我们称之为cpp1.cpp(。
现在我的问题是: 我在与 dir1 相同级别的dir2上还有另一个dir2,它有自己的CMakeLists.txt我正在尝试在其中编译位于dir2中的另一个 cpp 文件(我们称之为cpp2.cpp(。这个新的 cpp 使用或者应该使用在dir1标头和 cpp 文件中声明和定义的一些函数和类。 在我的cpp2 中.cpp我正在做:
#include "header1_from_dir1.h"
#include "header2_from_dir1.h"
这给了我这个错误: 错误: 未在此范围内声明"func_name"func_name(param1( ^~~~~~~~~~~~
当我尝试将其包含在相对路径中时,它可以编译并正常工作:
#include "../dir1/header1_from_dir1.h"
#include "../dir1/header2_from_dir1.h"
为什么会这样? 如何修改 CMakelists.txt以正确"查看">dir1中定义的函数?
简而言之,在CMakeLists中:
include_directories(../dir1)
add_executable(cpp2 cpp2.cpp ../dir1/cpp_header1.cpp ../dir1/cpp_header2.cpp)
target_include_directories(cpp2 PUBLIC ./dir1)
target_link_libraries(some_library_from_another_place)
install(TARGETS cpp2 DESTINATION ${CMAKE_SOURCE_DIR}/bin/${TARGET_LOCATION})
目录结构:
.
|-- dir1
| |-- bin
| |-- build
| |-- header1_from_dir1.h
| |-- header2_from_dir1.h
| |-- cpp_header1.cpp
| |-- cpp_header1.cpp
| |-- cpp1.cpp // this uses functions and clases from above files
| `-- CMakeLists.txt // this is for above cpp1.cpp
|-- dir2
| |-- bin
| |-- build
| |-- cpp2.cpp // this uses functions and clases from
// dir1/cpp_header1.cpp
| `-- CMakeLists.txt // this is for above cpp2.cpp and have briefly
// described its contents
来自target_include_directories文档:
INSTALL_INTERFACE表达式中允许使用相对路径,并相对于安装前缀进行解释。
所以相对路径不是你想要的。您需要指定绝对路径,以便正确解释以进行编译。使用CMAKE_CURRENT_SOURCE_DIR
指定当前源目录中的相对路径。
如何修改 CMakelists.txt以正确"查看"dir1 中定义的函数?
您可以通过以下方式修改项目:
项目结构:
┣ dir1
┃ ┣ test.cpp
┃ ┗ test.h
┣ dir2
┃ ┣ CMakeLists.txt
┃ ┗ cpp2.cpp
┗ CMakeLists.txt
根
CMakeLists.txt:
project(test)
add_subdirectory(dir2)
目录1
测试.h
#pragma once
void hello();
测试.cpp
#include "test.h"
#include <iostream>
void hello()
{
std::cout << "hello" << std::endl;
}
目录2
CMakeLists.txt:
add_executable(cpp2)
target_sources(cpp2 PRIVATE cpp2.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../dir1/test.cpp)
target_include_directories(cpp2 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../dir1)
CPP2.cpp:
#include <test.h>
int main()
{
hello();
}
更好的方法是从dir1
制作库,将其导出,然后导入dir2/CMakeLists.txt
。
希望这有帮助。
- .cpp和.h文件中的模板专用化声明
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如果 x.h 仅由函数声明组成,为什么有必要在 x 中包含 x.h.cpp
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 在.cpp文件之间传递结构声明,而不使用全局头文件
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP
- 当我可以在头文件中声明和定义所有文件时,为什么要创建一个.cpp文件?
- C++文件中.cpp静态对象声明
- 如果您只需要在 .h 文件中声明函数.cpp是否需要在 .h 文件中声明函数?
- 何时在抽象类 cpp 中声明受保护的字段
- 在 h 和 cpp 文件中单独声明和实现模板有时有效,有时会出现链接器错误
- 为什么我的.cpp文件无法解析 .h 文件中声明的变量?
- Cpp 什么是字符 a 的声明 [10][100]
- 重新声明C++内置类型"wchar_t"Windows 10 过剩 CPP
- 在 Cpp 标头中声明的常量变量应具有多少个符号条目
- 在 cpp 正文中声明方法时未定义的符号
- 如何在CPP中声明Array和Init
- 如何将数据类型声明从.cpp文件传输到 .cu 文件
- 在 cuda 内核中声明 CPP 对象