Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 1.49 KB

File metadata and controls

42 lines (34 loc) · 1.49 KB

Step 6: Example Program & Usage

A library is useless if no one knows how to use it. Step 6 focuses on creating a "Driver Program" (or Client Application) that uses our library to do something real.

The Demo Program (examples/demo.c)

1. Header Includes

#include "scanner.h"
#include "tokenizer.h"
#include "stats.h"

We include the Public API. Notice we do NOT include .c files. We only need the promises (headers).

2. Dependency Injection

In C, we often use a pattern called Dependency Injection manually.

Scanner scanner;
scanner_init(&scanner, input);

Tokenizer tokenizer;
tokenizer_init(&tokenizer, &scanner); // Inject scanner into tokenizer

The Tokenizer needs a source of characters. Instead of hardcoding it to read a file, we "inject" the scanner. This makes the Tokenizer flexible.

3. The Main Loop

while (token.type != TOKEN_END) {
    // Process token...
}

This is the standard Consumption Loop. You assume the stream of tokens is infinite until you hit the special TOKEN_END signal.

Linking

When checking if your code works, you need two steps:

  1. Compile: Convert demo.c to demo.o. It needs standard headers.
  2. Link: Combine demo.o + libtxtengine.a -> demo.exe.
    • The Linker resolves symbols like scanner_next by looking inside the library.

What you learned

  • Client Code: How strictly separated the user code is from the library code.
  • Integration: Putting all the modules together to solve a problem.