I have a c++ project with several subdirectories, e.g.
src/
CMakeLists.txt
main.cpp
module1/
CMakeLists.txt
code.cpp
code.h
module2/
CMakeLists.txt
code2.cpp
Run Code Online (Sandbox Code Playgroud)
It seems that the two ways to deal with this in cmake is to either use add_subdirectory(module1) or include(module1) in my src/CMakeLists.txt. Somewhere I read, that the include use is regarded legacy/deprecated. My src/module1/CMakeLists.txt looks like this:
include_directories(${CMAKE_CURRENT_LIST_DIR})
set( SRCS
${SRCS}
${CMAKE_CURRENT_LIST_DIR}/code.cpp
)
set( QT_FILE_HEADERS
${QT_FILE_HEADERS} code.h
)
Run Code Online (Sandbox Code Playgroud)
If I try to use the add_subdirectory method and want to usecode.h in main.cpp I have to write #include "module1/code.h". If I do the include method of adding module1, I can simply write #include "code.h". I would prefer not to specify the relative path of the include files when I use them somewhere else, is there a way to achieve this using the add_subdirectory method? I thought the include_directories line should have taken care of that.
这不是你应该如何制作模块——当然你可以这样做,它可以工作,但它不是很有用。根据您的布局,只需module1/code.cpp在主CMakeLists.txt文件中引用即可。
但是,如果您想使用模块,请将每个模块都设为一个单独的静态库。这将真正简化事情!
在src/CMakeLists.txt写:
add_subdirectory(module1)
add_executable(myprogram main.cpp)
target_link_libraries(myprogram module1)
Run Code Online (Sandbox Code Playgroud)
在src/module1/CMakeLists.txt写:
add_library(module1 STATIC code.cpp)
target_include_directories(module1 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
Run Code Online (Sandbox Code Playgroud)
这样,您只从module1CMake 脚本传回一件事:module1目标。你main不需要知道里面发生了什么。如果代码module1需要特定的外部库,将它们链接到那里,主 CMake 脚本不需要知道它。只需链接到module1,所有魔法都将在幕后发生,您的程序将使用正确的包含目录进行编译并链接到正确的库。