» Quick Introduction to C » 2. Advanced » 2.4 Build a Binary

Build a Binary

Input and Output

In C, interacting with the user console is made possible through the stdio.h (standard input output library) header, which contains methods for input and output.

#include <stdio.h>

int main() {
    char name[50];
    int age;

    printf("Enter your name: ");
    // Use scanf to read a string (name) from the user
    scanf("%s", name);

    // Prompt the user for their age
    printf("Enter your age: ");
    // Use scanf to read an integer (age) from the user
    scanf("%d", &age);

    printf("Hello, %s! You are %d years old.\n", name, age);
    return 0;
}

Program Arguments

In C, you can take command-line arguments using the argc and argv parameters in the main function. argc is the number of command-line arguments, and argv is an array of strings containing the arguments.

#include <stdio.h>

int main(int argc, char *argv[]) {
    // Check if there are at least two arguments
    // (program name counts as the first argument)
    if (argc >= 2) {
        // Print the program name
        printf("Program name: %s\n", argv[0]);

        // Iterate through the arguments
        printf("Arguments:\n");
        for (int i = 1; i < argc; i++) {
            printf("Argument %d: %s\n", i, argv[i]);
        }
    } else {
        printf("Usage: %s <arg1> <arg2> ...\n", argv[0]);
    }
    return 0;
}

Compilation

Compilation is the process of translating human-readable C source code into machine-executable code. It involves 4 steps: preprocessing, compiling, assembly and linking.

Preprocessing

The preprocessor scans the source code and handles directives that start with #, such as #include and #define. It includes header files, expands macros, and performs conditional compilation.

Compiling

The preprocessed code is fed into the compiler, which translates it into assembly code or an intermediate representation. The compiler checks the syntax and semantics of the code and generates object files containing machine code.

Assembly

The assembler converts the assembly code into machine code or binary code that the computer's processor can understand. This step produces object files with a ".o" extension.

# Compile main.c to object
gcc -c -std=c11 src/main.c -o main.o
# Compile calculator.c to object
gcc -c calculator.c -o target/calc.o

GCC

GCC, the GNU Compiler Collection. Learn more about GCC here: https://gcc.gnu.org/

Linking

The linker takes the object files generated during compilation and combines them with any necessary libraries to create the final executable file. It resolves references to functions and variables, assigns memory addresses, and produces an executable file.

# Link objects and create executable
gcc main.o target/calc.o -o bin/myprog