CMake测试子项目编译时出现第三方头文件找不到的错误
Alright, let's tackle this CMake header include issue you're facing. The root problem here is straightforward: your test subproject doesn't have access to the third-party LL library's include paths, even though your main application does. Let's fix this properly using modern CMake practices (which avoid the scoping pitfalls of old-school include_directories):
Ditch global
include_directoriesfor target-specific setupinclude_directoriesapplies paths only to the current CMake directory and its immediate subdirectories. Since your test subproject is likely in a separate folder, it doesn't inherit those paths. Instead, use target-specific includes that propagate dependencies automatically.Update your
datagramparserslibrary to expose LL's include path
In the CMakeLists.txt for yourdatagramparserslibrary, replace any reliance on parentinclude_directorieswithtarget_include_directoriesusing thePUBLICkeyword. This ensures any target linking againstdatagramparsersgets access to LL's headers:# Inside datagramparsers/CMakeLists.txt target_include_directories(datagramparsers PUBLIC ${PATH_TO_LL_ROOT_INCLUDE} # Replace with the actual root path containing the "LL/" folder # Add other public includes here if needed )Link your test target to
datagramparsers
In your test subproject's CMakeLists.txt, make sure you link againstdatagramparsers(not just add source directories). When you link, thePUBLICincludes fromdatagramparserswill automatically be added to your test target's include path:# Inside your test subproject's CMakeLists.txt add_executable(your_test_target test_file1.cpp test_file2.cpp) target_link_libraries(your_test_target PRIVATE datagramparsers # This pulls in LL's headers automatically easyloggingpp )Debug if needed
If you want to confirm the include paths are set correctly for your test target, add this debug snippet to your test's CMakeLists.txt:get_target_property(TEST_INCLUDE_PATHS your_test_target INCLUDE_DIRECTORIES) message(STATUS "Test target include paths: ${TEST_INCLUDE_PATHS}")Run CMake and check the output—you should see LL's root include directory listed there.
The core idea here is using CMake's target-based dependency system instead of global directory settings. This ensures dependencies are properly propagated between targets, eliminating "missing header" issues like this one.
内容的提问来源于stack exchange,提问作者rbaleksandar

