Learning C, No. 1: Hello World

A minimal C Program

#include <stdio.h>
main() {
    puts("Hello, World!");
}

This very minimal Hello World can be compiled with gcc smaller than version 14. Yes it issues a warning because the missing return type for main, but it compiles.

After version gcc-14 you have to explicitly define the return type as int or an error is thrown like so:

    gcc-14 hello.c
    base.c:3:1: error: return type defaults to 'int' [-Wimplicit-int]
        3 | main() {
          | ^~~~

A minimal, modern, valid Hello World

In order to comply with more recent compilers, the helloworld_minimal.c example adds return types:

#include <stdio.h>
int main() {
    puts("Hello, World!");
    return 0;
}

Explanations line after line

  1. An include mechanism if there are external libraries are needed, like here the puts function

  2. An main function as entry point older C compiler where OK with return type ‘void’

  3. A simple function like puts that does something, puts is defined in the included <stdio.h> library

  4. A return function that satisfies the function type for main also older C compilers did not need that

A Hello World version that showcase more of C features and arguments

The example helloworld_arguments.c show these features:

The compilation process

The compiler gcc in this example works in two steps

  1. Compile .c files into object.o files with gcc
  2. Link object.o files into executables

Common arguments given to gcc:

A minimal Makefile

Sources

helloworld_minimal.c

#include <stdio.h>

int main() {
    puts("Hello, World!");

    return 0;
}

helloworld_arguments.c

#include <stdio.h>

void print_name(char *name) {
    while (*name) {
        putchar(*name++);
    }
}

int main(int argc, char **argv) {

    int i;
    for (i = 1; i < argc; i++){
        printf("%s ", "Hello");
        print_name(argv[i]);
        printf("\n");
    }

    return(0);
}

Makefile

.PHONY: all clean 

# specify C compiler
CC=gcc 
# specify compile flags
CFLAGS=-Wall -g

all: helloworld_minimal helloworld_arguments
    ./helloworld_minimal 
    ./helloworld_arguments 'John'


# create object.o files
#
helloworld_minimal.o: helloworld_minimal.c
    $(CC) $(CFLAGS) -c $< -o $@

helloworld_arguments.o: helloworld_arguments.c
    $(CC) $(CFLAGS) -c $< -o $@

# link object.o files to exetables
helloworld_minimal: helloworld_minimal.o
    $(CC) $^ -o $@ 

helloworld_arguments: helloworld_arguments.o
    $(CC) $^ -o $@ 

clean:
    rm -f *.o
    rm -f helloworld_minimal
    rm -f helloworld_arguments

Download

1_hello-world-in-c_20240906155004.zip

created by:   ben  
last edited:  06.09.2024, 13:45:00  
generated:    06.09.2024, 15:50:04