在进行C/C++相关开发时候,经常会遇到段错误,这个时候比较无语的一点就是Linux Shell终端下几乎不会输出太多有用的信息,大多数情况下打印信息如下:Segmentation fault (core dumped)
,错误如下图所示:
有大佬专门开发了一款工具,叫做backward-cpp用来解决这个问题,该工具假设你用Cmake构建项目。其Github仓库地址为:https://github.com/bombela/backward-cpp
如下图所示:
最近我需要将在Windows10下编写的VC++控制台程序移植到Linux下,发行版是CentOS7,使用CMake进行项目的编译和管理,好不容易能够运行了,但是生成可执行文件,然后运行出现断错误:Segmentation fault (core dumped)
没有什么提示,参考了用GDB调试程序的设置 Segmentation fault(Core Dump)调试这篇文章:
但是对于我的项目没有什么效果,
最后看到调试段错误Segmentation fault (core dumped)打印详细报错信息,按照这篇博客的步骤下载了backward-cpp到CMakeLists.txt的项目同级目录下:
git clone https://github.com/bombela/backward-cpp.git
官方文档给了CMake的两种整合方式,我在项目中使用的是第一种:As a subdirectory
在这种情况下,您有一个子目录,其中包含Backward的整个存储库(例如:使用git-submodules),在这种情况下,您可以执行以下操作:
add_subdirectory(/path/to/backward-cpp)
# This will add backward.cpp to your target
add_executable(mytarget mysource.cpp ${BACKWARD_ENABLE})
# This will add libraries, definitions and include directories needed by backward
# by setting each property on the target.
add_backward(mytarget)
我的CMakeLists.txt文件如下:
project(DB2HJ212_yc_towns)
cmake_minimum_required(VERSION 2.8)
set (VERSION 1.0.0)
add_definitions (-DCMAKE -DVERSION=\"${VERSION}\")
#add_definitions("-DUSE_MOSQUITTO")
#add_definitions("-DPUGIXML_HEADER_ONLY")
add_subdirectory(./backward-cpp)
INCLUDE_DIRECTORIES(../include)
INCLUDE_DIRECTORIES(/usr/local/include)
INCLUDE_DIRECTORIES(/usr/local/include/mariadb)
set(GB212_SRC
./DataFile.cpp
./DataUpload.cpp
./HJ212Generator.cpp
./MYSQL2File.cpp
./RemoteServer.cpp
#../include/pugixml.cpp
./SetupConfig.cpp
./main.cpp)
set(CMAKE_CXX_FLAGS "-g -Wall")
if(CMAKE_COMPILER_IS_GNUCXX)
set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
endif(CMAKE_COMPILER_IS_GNUCXX)
if(WIN32)
set(BOOST_ROOT_DIR D:\\env\\local\\boost_1_69_0)
endif(WIN32)
set(ENV_DYNAMIC_LIBS "/usr/local/lib") # 动态库路径(自定义的)
# 在搜索Boost的package之前,可以通过设置一些变量来帮助boost库的查找
#set (BOOST_ROOT /usr/local/)
#set (BOOST_INCLUDEDIR ${BOOST_ROOT}/include)
#set (BOOST_LIBRARYDIR ${BOOST_ROOT}/lib)
find_library(Boost REQUIRED COMPONENTS thread)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIRS})
# ========================================
# Include projects
# ========================================
LINK_DIRECTORIES(/usr/local/lib64)
set(GB212_LIBS
pthread
boost_thread
boost_locale
mariadb
mariadbclientpp
pugixml)
add_executable(${PROJECT_NAME} ${GB212_SRC} ${BACKWARD_ENABLE})
add_backward(${PROJECT_NAME})
target_link_libraries(${PROJECT_NAME} ${GB212_LIBS})
install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
添加了backward-cpp
之后再次运行可执行程序DB2HJ212_yc_towns
运行结果如下图所示:
可以看到在CMakeLists.txt中添加了backward-cpp
之后出现了调试堆栈错误信息了。