"Hello, World!" in C

"Hello, World!" in C

Open up a terminal and enter the following commands.

$ cd ~
$ mkdir -p ~/src/c/hello_world/
$ cd src/c/hello_world/
$ vim hello_world.c

Place the following code in hello_world.c and save.

#include <stdio.h>
#include <stdlib.h>

int main (void) {
	puts("Hello, World!");
	return EXIT_SUCCESS;
}

Now you need to compile the program.

$ gcc hello_world.c
$ ls
a.out	hello_world.c

The new file created a.out is the binary which we will execute.

Run the file.

$ ./a.out
Hello, World!

Recompile it again, now with a flag -S, which produces and outputs the assembly code file. Output the new hello_world.s file to see the assembly.

$ gcc -S hello_world.c
$ ls
a.out	hello_world.c	hello_world.s
$ cat hello_world.s
	.file	"hello_world.c"
	.text
	.section	.rodata
.LC0:
	.string	"Hello, World!"
	.text
	.globl	main
	.type	main, @function
main:
.LFB6:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	leaq	.LC0(%rip), %rdi
	call	puts@PLT
	movl	$0, %eax
	popq	%rbp
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE6:
	.size	main, .-main
	.ident	"GCC: (GNU) 9.2.0"
	.section	.note.GNU-stack,"",@progbits

Subscribe to Linux Developer

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe