A C program prints a usage message by calling printf (or fprintf) with a short synopsis of the accepted arguments, then exiting with a non-zero status so scripts can detect the error. The message belongs on standard error, not standard output. The reliable trigger condition is "the command line doesn't match what the program expects," which you test in main before doing any real work. From there you choose the exit code, decide whether to print a one-line hint or a full synopsis, and make sure the same text is reused everywhere instead of being retyped. This guide walks through the mechanics, the conventions behind them, and the failure modes that make usage messages unhelpful.

Start With the Contract Your Program Expects

Before writing a single line of output code, write down the command-line contract in plain language. A usage message is only useful if it describes the same rules the code enforces, and most bad usage text comes from drift between the two.

A minimal contract has four parts:

The program name as the user invokes it (often argv, but see the caveats below). The required operands, in order, with their types. Optional flags or subcommands, with any default behavior. The exit status meaning, at least for the failure case.

For a small tool, that might read: "One required input file, an optional -o output path defaulting to standard output, and -h/--help to print usage and exit successfully." Every one of those facts should appear in the message. Nothing should appear in the message that the program doesn't actually accept.

The reason to do this on paper first is that usage text is documentation embedded in code. Once it is a string literal in main, it tends to rot. Writing the contract first gives you a reference to check against when arguments change.

Choose the Right Output Stream and Exit Status

Two conventions do most of the work here, and getting them right separates a polite program from an annoying one.

Print to standard error when the message reports a mistake. Standard output is for the program's actual results; standard error (stderr) is for diagnostics. If you print usage to stdout on an error, a user who pipes your output to a file or another program will get the usage text mixed into their data. The fix is fprintf(stderr, ...) instead of printf(...).

Exit non-zero on error, zero on a deliberate help request. A missing or malformed argument is a failure, so return EXIT_FAILURE (defined in <stdlib.h>, conventionally 1). But when the user explicitly asks for help with -h or --help, that's a successful request; print the same text to stdout and return EXIT_SUCCESS. Shell scripts and build systems depend on this distinction, and users notice when myprog --help | less works instead of failing.

There is a third case worth naming: a usage error caused by bad flag syntax is still a usage error. Don't try to "helpfully" continue with defaults unless the documentation says defaults exist. Silent fallback hides typos, and a typo'd filename that quietly writes to the default path is worse than a one-line error.

Build the Message as a Single Reusable Function

The cleanest pattern keeps the usage text in one place and lets callers decide the stream and exit behavior. Here's a compact version:

Three design choices are baked into that snippet.

The FILE *stream parameter means the same text serves both the error path (stderr) and the help path (stdout) without duplication. Duplicated usage text is the most common source of inconsistency in small C tools.

The const char *prog parameter keeps the program name as data rather than hardcoding it. That matters for the reasons in the next section.

The format uses %s for the program name and no other conversions, so there is no risk of a mismatch between format specifiers and arguments. If you later add a placeholder, keep the -Wformat warnings enabled; GCC and Clang will catch type mismatches at compile time when you build with -Wall -Wextra.

For programs with more options than fit comfortably in a fprintf, it's fine to split the text into several calls or store the lines in a static const char *const array and loop. The key property is that the whole message lives in one function that every caller uses.

Decide What Goes Into the Message

Usage messages fail in two opposite directions: too terse to act on, and so long they scroll past the error. The test is whether a user who has never seen the program can fix their command from the message alone.

Include these, in roughly this order:

1: The invocation line, starting with Usage: and the program name. 2: A one-sentence description of what the program does, if the name isn't self-explanatory. 3: Required arguments and their meaning. 4: Options, one per line, with the argument placeholder and a short explanation. 5: A pointer to fuller documentation if one exists (See man myprog for details.).

Leave out version numbers, author credits, license text, and long examples. Those belong in --version output or the man page. A usage message is a correction, not a manual.

Keep option descriptions parallel in grammar and length. "Write output to OUTPUT" and "Suppress progress messages" sit better together than a mix of imperatives, noun phrases, and sentences. Parallelism is what makes a list scannable.

One judgment call: whether to show the full option list on every error, or only a one-line Try 'myprog --help' for more information. For programs with three or four options, print the full message. For programs with dozens, a short pointer avoids drowning the actual error. Either is defensible; the mistake is inconsistency between the error path and the -h path.

Handle argv Without Trusting It

Using argv as the program name is conventional and usually correct, but it has two quirks worth knowing.

First, argv can be NULL in rare circumstances. The C standard permits a hosted environment to pass an empty argument list, though in practice this is exotic. A defensive check costs one line:

Second, and more practically, argv is whatever the caller typed or whatever exec was given. If the program was launched through a symlink, a wrapper script, or an absolute path, the printed name reflects that. That's usually desirable: the message echoes what the user actually ran. But it also means the name can contain a full path, which makes a long usage line. Two common fixes are to strip the directory with strrchr(prog, '/') and use the basename, or to print the bare name and let the invocation line stand alone.

Do not pass argv directly as a format string. fprintf(stderr, argv); is a format-string vulnerability, since % sequences in a filename would be interpreted. Always print it with %s.

If you write the message with a hardcoded name instead, that's also acceptable, and arguably more stable for installed tools. Just pick one approach per program and use it everywhere.

Wire Up the Trigger: Parse, Detect, Print, Exit

The control flow is the part people most often get subtly wrong, so here is an ordered sequence that works for most single-command tools.

Prerequisite: a main that receives argc and argv, and a usage function already in place.

1: Check for the help flag before anything else. Scan the arguments for -h or --help. If found, call print_usage(stdout, prog) and return EXIT_SUCCESS;. Doing this first means a user can always get help even if other arguments are wrong. 2: Check the argument count. If the number of operands doesn't match the contract, call print_usage(stderr, prog) and return EXIT_FAILURE;. Print this before trying to interpret arguments, so the message doesn't depend on parsing. 3: Parse options in a loop, collecting operands as you go. On an unrecognized option, print a one-line error to stderr naming the bad token, then the usage text, then return EXIT_FAILURE. 4: Validate operands (file exists, number in range, mutually exclusive flags not combined). Each failure should produce a specific message plus, usually, the usage text. 5: Only after all of that, execute the program's real work.

Two structural notes. First, steps 2 through 4 should funnel through a single helper so the "print to stderr and exit" pattern isn't copy-pasted:

A variadic helper that formats a short reason, appends the usage text, and calls exit(EXIT_FAILURE) keeps the call sites to one line. Just be careful with variadic forwarding; a simple version that takes a preformatted string is easier to get right than one that re-implements vprintf unless you need the flexibility.

Second, exit versus return from main: both work, but return from main is easier to reason about in small programs and skips atexit-related surprises for callers if you ever refactor main into a reusable function. Either is fine; consistency matters more than the choice.

Success check: compile with warnings on (cc -Wall -Wextra -Wformat=2), run the program with no arguments, and confirm that the usage text appears on stderr and that echo $? reports a non-zero status. Then run it with --help and confirm the text appears on stdout with a zero status. Finally, confirm a successful run produces no usage text at all.

Test the Behavior, Not Just the Text

A usage message is a user interface, so test the interface. Four checks catch most problems:

Stream separation: myprog 2>/dev/null should print nothing on a successful run and nothing on an error once stderr is discarded. myprog --help 2>/dev/null should still show the text. Exit status: myprog; echo $? should be non-zero; myprog --help; echo $? should be zero. Wrap these in a shell test in your Makefile or CI so a refactor can't silently flip them. Text accuracy: run every documented flag once and confirm it does what the message says. This is the check that prevents drift, and it's cheap when the option list is short. Format-string safety: run the program with an argument containing %n or %s, e.g. ./myprog '%s%s', and confirm the output is literal text and not a crash. This catches the fprintf(stderr, argv) mistake described earlier. Building with -Wformat-security (implied by -Wformat=2 on GCC) flags constant-format-string problems at compile time.

For larger projects, a shell script that asserts on exit codes and greps stderr for Usage: is enough; you don't need a test framework for this. The point is that the behavior is pinned.

Common Failure Modes and How To Read Them

When a usage message misbehaves, the symptom usually points to one of a handful of causes.

The message appears during normal successful runs. Almost always a missing return or exit after the usage call, so execution falls through into the rest of main. Check for a break where you needed a return.

The message is invisible in a pipeline. It went to stdout. Confirm the fprintf uses stderr on the error path.

The program name prints as garbage or crashes. Either argv was passed as the format string, or the prog pointer points at something that went out of scope. Use %s and keep the pointer to a const string that outlives the call.

The shell reports "command not found" instead of the usage message. That's a different problem: the binary isn't on the path, so your message never runs. Check echo $PATH and whether you built the program at all.

The message is correct but the exit code is zero. Look for an exit(EXIT_SUCCESS) or a bare return 0 placed after the usage call, or a main declared as returning a value that's ignored by a wrapper.

Output is truncated or garbled. If you're writing to a pipe and the program continues after printing, the process may exit before the buffer flushes. Exiting normally flushes stderr immediately (it's typically unbuffered) but stdout is line- or fully buffered. If you print usage to stdout and then call _exit or abort, the text can vanish. Use exit or return from main so flushable buffers drain.

A % in an option description produces odd output. You used a format string that treats % as a conversion. Escape it as %% inside the fprintf format, or print the description with fputs.

One stop condition: if the program is invoked by another program with arguments you don't control (a plugin host, a scheduler, a test harness), don't guess at the contract by adding a catch-all usage branch. Trace the actual invocation first. Adding a usage error for a legitimate call pattern breaks the caller, and the fix belongs in the caller's arguments, not in a more permissive parser.

Extending the Pattern Without Overbuilding

Once the basic flow works, a few small additions pay off, but more than a few starts to smell like a hand-rolled argument library.

A --version flag that prints to stdout and exits zero is standard and cheap. Keep it separate from the usage text; they answer different questions.

Long options (--output) are easy to add to a manual parser by checking for the exact string with strcmp, but as the count grows, the parsing code becomes the largest part of the program. At that point, a small, well-known argument-parsing library is the honest choice; the usage message can still come from your own function so the wording stays under your control. The threshold isn't fixed, but if you're writing help text for more than a handful of options while also writing a parser loop, you've crossed it.

Multiple subcommands (myprog convert INPUT, myprog check INPUT) change the shape of the message. The top-level usage lists subcommands; each subcommand has its own usage function. Keep the naming parallel so users can guess the pattern: myprog convert --help and myprog check --help should look like siblings.

Finally, resist the temptation to make usage text dynamically generated from the parser's data structures unless the project already has that infrastructure. For a single program, a hand-written string is clearer, easier to review, and easier to translate. Generate it only when the option count makes hand-maintenance a genuine bug source, and then test that the generated text still passes the "can a new user fix their command from this" check.

A Worked Example You Can Compile and Vary

Putting the pieces together for a program that takes one input file and an optional output path:

Compile with cc -std=c11 -Wall -Wextra -Wformat=2 -o myprog myprog.c. Then check the four behaviors: no arguments (stderr, exit 1), --help (stdout, exit 0), -o with no value (stderr, exit 1), and %s%s as an argument (literal text, no crash). The parser is intentionally simple; it treats - and -- specially only so a bare - can be an operand. If you later need -- as an end-of-options marker, add it as an explicit case rather than relying on the leading-dash test.

The example also shows the division of labor that keeps usage text honest: the parser owns the rules, and the usage function states them. When you add an option, you touch both, in the same commit. That habit is the real answer to "how do you use a C program to print a usage message" — the printing is one function call, but keeping it accurate is a discipline about where the message lives and when it fires.