Compile and Debug C Programs
In this step, you'll learn essential compilation and debugging techniques for C programs, including understanding compiler warnings, using compilation flags, and basic debugging strategies.
Create a Program with Intentional Errors
- Open the WebIDE and create a new file named
debug.c
.
- Enter the following code with some intentional errors:
#include <stdio.h>
int main() {
int x = 10;
int y = 0;
// Intentional division by zero
int result = x / y;
printf("Result: %d\n", result);
// Unused variable
int z = 5;
return 0;
}
Compile with Warnings
Compile the program with additional warning flags:
gcc -Wall -Wextra debug.c -o debug
Compilation Flags Explanation
-Wall
: Enables most warning messages
-Wextra
: Enables even more detailed warnings
Example compiler output:
debug.c: In function ‘main’:
debug.c:13:9: warning: unused variable ‘z’ [-Wunused-variable]
13 | int z = 5;
| ^
Use GDB for Debugging
Compile with debugging symbols:
gcc -g debug.c -o debug
Start debugging:
gdb ./debug
GDB Commands:
run
: Start the program
break main
: Set a breakpoint at the main function
print x
: Print the value of variable x
next
: Execute next line
quit
: Exit GDB
(gdb) run
Starting program: /home/labex/project/debug
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGFPE, Arithmetic exception.
0x0000555555555167 in main () at debug.c:8
8 int result = x / y;
(gdb) print x
$1 = 10
(gdb) break main
Breakpoint 1 at 0x555555555155: file debug.c, line 4.
(gdb) next
Program terminated with signal SIGFPE, Arithmetic exception.
The program no longer exists.
(gdb) quit
GDB shows a division by zero error at line 8. The program crashes due to an arithmetic exception.
Fix the Program
Modify debug.c
to handle division safely:
#include <stdio.h>
int main() {
int x = 10;
int y = 2; // Change from 0 to a non-zero value
if (y != 0) {
int result = x / y;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero!\n");
}
return 0;
}
Recompile and run:
gcc -Wall -Wextra debug.c -o debug
./debug
Output:
Result: 5
Troubleshooting Tips:
- Always compile with
-Wall -Wextra
- Pay attention to compiler warnings
- Use GDB for complex debugging scenarios
- Add error checking for potential runtime issues