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
	

Print variable "name" value;

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

Print variable "name" type;

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

Variable is a string constant. Execute next line to end;

	(gdb) n
	
Development Index

This is part of the Hive System Documentation. Copyright (C) 2018 c9 team. See the file Gnu Free Documentation License for copying conditions.