如何配置CMake的add_executable()引入父目录同级子目录下的file2.h?
Hey there! Let's break down your two CMake questions with practical, easy-to-follow examples.
add_executable()中引入父目录同级子目录下的文件 First off, you'll need to do two key things: tell CMake where to find the header files from that sibling directory, and include any source files from there that need to be compiled into your executable.
Let's use a concrete directory structure to make this tangible:
my_project/ ├── my_app/ │ ├── main.cpp │ └── CMakeLists.txt # This is the file we'll edit └── common_utils/ ├── helper.h └── helper.cpp
Here's how to set up the my_app/CMakeLists.txt:
cmake_minimum_required(VERSION 3.10) project(MyApp) # Get the path to the sibling common_utils directory set(COMMON_UTILS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../common_utils") # Create the executable, including the source file from the sibling directory add_executable(MyApp main.cpp "${COMMON_UTILS_DIR}/helper.cpp") # Tell the executable where to find the header files (modern CMake approach) target_include_directories(MyApp PRIVATE "${COMMON_UTILS_DIR}")
Quick notes:
CMAKE_CURRENT_SOURCE_DIRrefers to the folder where the currentCMakeLists.txtlives, so../common_utilsjumps up one level and into the sibling directory.target_include_directorieswithPRIVATEensures this header path only applies toMyApp(it won't leak to other targets that might depend on it). This is the recommended modern CMake practice over globalinclude_directories().- If the sibling directory only has header files (no
.cppfiles to compile), you can skip adding the.cpptoadd_executable()—just keep thetarget_include_directoriesline so your code can#includethose headers.
add_executable()添加file2.h文件 First, let's assume a typical project structure where file2.h lives in a separate include directory:
my_project/ ├── src/ │ ├── main.cpp │ └── CMakeLists.txt └── include/ └── file2.h
A quick clarification: Header files don't get compiled directly, so technically you don't need to list file2.h in add_executable(). However, adding it has two benefits: your IDE will recognize it as part of the project, and CMake will trigger a recompile if the header changes.
Here's the setup for src/CMakeLists.txt:
cmake_minimum_required(VERSION 3.10) project(MyProject) # Define the path to the include directory set(INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../include") # Create the executable—we include file2.h here for IDE visibility and rebuild triggers add_executable(MyExecutable main.cpp "${INCLUDE_DIR}/file2.h") # Tell the executable where to find the header files target_include_directories(MyExecutable PRIVATE "${INCLUDE_DIR}")
Now in main.cpp, you can simply write:
#include "file2.h"
If file2.h were in the same directory as main.cpp, you could skip the target_include_directories line and just list the header in add_executable() (if desired)—CMake will automatically find it in the current source directory.
内容的提问来源于stack exchange,提问作者Ben Schroeder

