Development Index

C & GDB

Hello World

Create file hello.c with;

	#include <stdio.h>

	int main() {
	    printf("Hello World!");
	    return 0;
	}
	

Compile;

	$ gcc -Wall hello.c -o hello
	

Run;

	$./hello
	Hello World!
	

Multiple Sources

To organize code in multiple files split above example in main.c, hello.c and hello.h. Content of main.c;

	#include "hello.h"

	int main() {
	    hello("world");
	    return 0;
	}
	

Header file contains declaration of the function hello, content of hello.h;

	void hello(const char* name);
	

Implementation of hello function in hello.c;

	#include <stdio.h>
	#include "hello.h"

	void hello(const char* name) {
	    printf("Hello, %s!\n", name);
	}
	

Compile;

	$ gcc -Wall main.c hello.c -o hello
	

Makefile

Make reads a Makefile by default on current directory, Makefile defines targets, for example executables and their dependencies, for example object files and source files.

Create Makefile;

	CC=gcc
	CFLAGS=-Wall

	hello: main.o hello.o

	clean:
		rm -f hello main.o hello.o
	
	$ touch NEWS README AUTHORS ChangeLog
	

Debug

To use gdb you need to compile program with -g flag. Change Makefile

	CC=gcc
	CFLAGS=-Wall -g

	hello: main.o hello.o

	clean:
		rm -f hello main.o hello.o
	
	$ gdb hello
	

Set break point;

	(gdb) break main
	

To start the program you can type run, this way gdb will try to run the program until the end. If program crash, gdb will stop it for debuging. Start program;

	(gdb) run
	

Step in next line;

	(gdb) s
	

Execute next line;

	(gdb) n
	

To start gdb in TUI mode press;

Ctrl-x A
Enter or leave TUI.
Ctrl-x 1
TUI with only one window.
Ctrl-x 2
TUI with more than two windows.
Ctrl-x o
Change active window.
Ctrl-x s
TUI single key mode.
Ctrl-L s
Refresh screen.
Up
Scroll
Down
Scroll
Left
Scroll
Right
Scroll

Run again and step in hello function, to print variable "name" value and type;

        (gdb) print name
        $1 = 0x4005b0 "world"
        (gdb)
        

Print variable name type;

        (gdb) ptype name
        type = const char *
        (gdb)
        

Variable is a string constant, continue reading Elements.

Development Index

This is part of the c9-doc Manual. Copyright (C) 2016 c9 team. See the file Gnu Free Documentation License for copying conditions.