如何制作 cmakelists.txt编译使用在其他地方声明和实现的函数和类的 CPP

how to make cmakelists.txt compile cpp that uses functions and classes declared and implemented in some other place

本文关键字:声明 CPP 实现 函数 方声明 编译 txt cmakelists 何制作 其他      更新时间:2023-10-16

我在 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

希望这有帮助。