在大型项目中,会有多个目录下的源文件需要编译。希望可能针对性的配置需要保留调试信息的源文件,而不是整个项目的源文件都保留调试信息。
CMake编译时部分源文件保留调试信息
一个ros2项目的部分目录结构如下:
.
├── CMakeLists.txt
├── include
│ ├── tracking
│ │ ├── matcher.hpp
│ │ ├── tracker.hpp
│ │ ├── tracker_manager.hpp
│ │ └── utility.hpp
│ └── utility
│ ├── timer_consume.hpp
│ ├── translator_utils.hpp
│ └── utils.hpp
├── src
│ ├── file1.cpp
│ ├── file2.cpp
│ ├── tracking
│ │ ├── CMakeLists.txt
│ │ ├── matcher.cpp
│ │ ├── tracker.cpp
│ │ ├── tracker_manager.cpp
│ │ └── utility.cpp
│ └── utility
│ ├── CMakeLists.txt
│ ├── timer_consume.cpp
│ ├── translator_utils.cpp
│ └── utils.cpp
CMakeLists.txt
# CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(CMakeCompileWithDebugInfo)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE Release)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g")
elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
endif()
find_package(foxglove_msgs REQUIRED)
find_package(OpenCV REQUIRED)
set(SOURCE_LIST
${CMAKE_CURRENT_SOURCE_DIR}/src/file1.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/file2.cpp
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/tracking)
list(APPEND SOURCE_LIST $<TARGET_OBJECTS:tracking_objs>)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/utility)
list(APPEND SOURCE_LIST $<TARGET_OBJECTS:utility_objs>)
add_library(${PROJECT_NAME}_lib SHARED
${SOURCE_LIST}
)
target_include_directories(${PROJECT_NAME}_lib PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
${OpenCV_INCLUDE_DIRS}
# ...
)
target_link_libraries(${PROJECT_NAME}_lib
${OpenCV_LIBRARIES}
# ...
)
src/tracking/CMakeLists.txt
# src/tracking/CMakeLists.txt
add_library(tracking_objs OBJECT
${CMAKE_CURRENT_SOURCE_DIR}/matcher.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tracker_manager.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tracker.cpp
${CMAKE_CURRENT_SOURCE_DIR}/utility.cpp
)
target_include_directories(tracking_objs PUBLIC
${CMAKE_SOURCE_DIR}/include
)
target_link_libraries(tracking_objs
${OpenCV_LIBRARIES}
# ...
)
target_compile_options(tracking_objs PRIVATE -O3 -fPIC)
# if want to keep debug info, use -O0 -g
# target_compile_options(tracking_objs PRIVATE -O0 -g -fPIC)
src/utility/CMakeLists.txt
# src/utility/CMakeLists.txt
find_package(tf2 REQUIRED)
find_package(tf2_ros REQUIRED)
add_library(utility_objs OBJECT
${CMAKE_CURRENT_SOURCE_DIR}/utils.cpp
${CMAKE_CURRENT_SOURCE_DIR}/timer_consume.cpp
${CMAKE_CURRENT_SOURCE_DIR}/translator_utils.cpp
)
ament_target_dependencies(utility_objs
foxglove_msgs
tf2
tf2_ros
)
target_include_directories(utility_objs PUBLIC
${CMAKE_SOURCE_DIR}/include
${OpenCV_INCLUDE_DIRS}
# ...
)
target_link_libraries(utility_objs
# ...
)
target_compile_options(utility_objs PRIVATE -O3 -fPIC)
# if want to keep debug info, use -O0 -g
# target_compile_options(utility_objs PRIVATE -O0 -g -fPIC)
这里面值的注意的是,target_compile_options
中的 -g
选项,可以针对性的配置需要保留调试信息的源文件,而不是整个项目的源文件都保留调试信息。