从头创建Godbolt多文件项目时头文件无法识别的问题
The problem boils down to your CMake target not explicitly including the current directory in its header search path—even though the UI shows all files together. Here's how to resolve it:
1. Update Your CMakeLists.txt
Add a line to tell CMake to include the current source directory for your target:
cmake_minimum_required(VERSION 3.5) project(main.exe VERSION 1.0 LANGUAGES CXX) add_executable(main main.cpp source1.cpp source2.cpp) # Critical line: Add current directory to header search path target_include_directories(main PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
Why This Fixes It
CMAKE_CURRENT_SOURCE_DIR refers to the folder containing your CMakeLists.txt. By adding this as a private include directory, you ensure the compiler looks here for local headers like header.h when building your executable.
2. Double-Check Include Syntax
Make sure you're using the right include style in main.cpp:
#include "header.h" // Use quotes for project-local headers // Avoid <header.h>—that's reserved for system libraries
3. Quick Alternative: Direct Compiler Flag
If you prefer to use compiler flags instead of CMake commands, add -I. to the compiler options in your Compiler Explorer target settings. This explicitly adds the current directory to the include path, though using target_include_directories is the more maintainable CMake practice.
Final Checks
- Confirm
header.his named correctly (case matters on some systems, e.g.,Header.hvsheader.h). - Ensure the file is actually added to your Compiler Explorer project (the UI preview should show its content).
内容的提问来源于stack exchange,提问作者Adrian

