using vim to edit a cpp source file
vim bubblesort.cpp
The code is like this:
# include<iostream>
using namespace std;
void BubbleSort(int A[], int n)
{
int temp;
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n-1-i;j++)
{
if(A[j]>A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
}
}
void print(int A[],int n)
{
int i;
for(i = 0;i < n;i++)
cout << A[i] << ' ';
cout << endl;
}
int main()
{
int A[] = {5,34,67,32,43,7,75,34,4,55,63,99,22,123,143};
int len = sizeof(A)/sizeof(int);
print(A,len);
BubbleSort(A,len);
print(A,len);
}
Then we return to terminal, using
g++ -g -std=c++11 bubblesort.cpp -o bubble
In this command, -g used to generate gdb debug information which we will discuss later. -o to name the executed file.
To execute the code, use
.\bubblesort
Here I suppose you are at the dir. The outcome is
[xx@localhost gdb_example]$ ./bubblesort
5 34 67 32 43 7 75 34 4 55 63 99 22 123 143
4 5 7 22 32 34 34 43 55 63 67 75 99 123 143
[xx@localhost gdb_example]$
GDB is a debug tool under linux. If you want debug with gdb, you have to add -g in the gcc command:
$ g++ -g -std=c++11 xxx.cpp -o xxx
Start debug with the command:
1 $ gdb xxx
xxx is execute file.
2 $ gdb
dgb> file xxx
Useful command in gdb:
r for run
s for step
n for next (not go in to functions)
p [var] for print variable
b [lineNO][function] for set breakpoint at line or function
c for countinue
q for quit
More commands:
info breakpoints for show all breakpoints
delete for delete breakpoints
help [command]
set var
example:
[xx@localhost gdb_example]$ gdb bubblesort
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-110.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/xx/Documents/c++work/gdb_example/bubblesort...done.
(gdb) l
23 {
24 int i;
25 for(i = 0;i < n;i++)
26 cout << A[i] << ' ';
27 cout << endl;
28 }
29
30 int main()
31 {
32 int A[] = {5,34,67,32,43,7,75,34,4,55,63,99,22,123,143};
(gdb) b main
Breakpoint 1 at 0x40095e: file bubblesort.cpp, line 32.
(gdb) r
Starting program: /home/xx/Documents/c++work/gdb_example/bubblesort
Breakpoint 1, main () at bubblesort.cpp:32
32 int A[] = {5,34,67,32,43,7,75,34,4,55,63,99,22,123,143};
Missing separate debuginfos, use: debuginfo-install glibc-2.17-222.el7.x86_64 libgcc-4.8.5-28.el7_5.1.x86_64 libstdc++-4.8.5-28.el7_5.1.x86_64
(gdb) s
33 int len = sizeof(A)/sizeof(int);
(gdb) n
35 print(A,len);
(gdb) p len
$1 = 15
(gdb)