项目需要用到GDB调试,那就重新写一篇gdb入门教程。
包括了普通调试、多线程调试、多文件调试。
一、准备
首先创建三个文件main.cpp、test.h、test.cpp
//main.cpp
#include <stdio.h>
#include "test.h"
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 2
// 线程的运行函数
void* say_hello(void* argv)
{
CTest test;
test.func();
int tt = *(int*)argv;
cout << "Hello Runoob!" << endl;
sleep(100000);
return 0;
}
int func(int n)
{
int sum=0,i;
for(i=0; i<n; i++)
{
sum+=i;
}
return sum;
}
int main()
{
int i;
long result = 0;
for(i=1; i<=100; i++)
{
result += i;
}
//printf("result[1-100] = %d /n", result );
//printf("result[1-250] = %d /n", func(250) );
// 定义线程的 id 变量,多个变量使用数组
pthread_t tids[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; ++i)
{
//参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
int ret = pthread_create(&tids[i], NULL, say_hello, (void*)&i);
if (ret != 0)
{
cout << "pthread_create error: error_code=" << ret << endl;
}
else{cout << "create ok" << endl;}
}
//等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
sleep(100000);
return 1;
}
//test.h
#include <stdio.h>
class CTest
{
public:
CTest();
~CTest();
void func();
};
//test.cpp
#include "test.h"
#include <iostream>
CTest::CTest(){}
CTest::~CTest(){}
void CTest::func()
{
std::cout << "aaaaaaaaaaaaaaa" << std::endl;
}
//编译指令,生成a.out
g++ -g main.cpp test.cpp -lpthread
二、调试
1.定位到main文件中
2.定位到test.cpp的func函数
3.定位到不同线程中