aboutsummaryrefslogtreecommitdiff
path: root/man/usage.3
blob: ead0f2926fe09185e9255b5a40633df40e7d8484 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
.Dd 4 May 2024
.Dt USAGE 3
.Os
.Sh NAME
.Nm usage
.Nd print a program usage diagnostic
.Sh LIBRARY
.Lb mlib
.Sh SYNOPSIS
.In errors.h
.Ft void
.Fn usage "const char *s" "..."
.Sh DESCRIPTION
The
.Fn usage
macro prints a program usage diagnostic to the standard error.
The one-or-more program usages are provided as null-terminated strings to
.Fn usage ,
and the program name must be set via a prior invocation of
.Fn mlib_setprogname .
None of the provided arguments should be
.Dv nullptr .
.Sh EXAMPLES
The following call to
.Fn usage
prints a diagnostic showing the different command-line arguments that can
be provided to the example executable.
.Bd -literal -offset indent
#include <stdlib.h>

#include <errors.h>
#include <macros.h>   /* For lengthof() */
#include <mbstring.h> /* For U8() */
#include <optparse.h>
 
static const struct op_option opts[] = {
	{'a', U8(),       OPT_NONE},
	{'b', U8(),       OPT_NONE},
	{'h', U8("help"), OPT_NONE},
};

int
main(int argc, char **argv)
{
	mlib_setprogname("my-prog");

	rune opt;
	struct optparse op = mkoptparser(argv);
	while (opt = optparse(&op, opts, lengthof(opts))) {
		switch (opt) {
		/* … */
		case 'h':
			[[fallthrough]];
		default:
			/* Prints the following diagnostic:

			   Usage: my-prog [-ab]
			          my-prog -h
			 */
			usage("[-ab]", "-h");
			exit(opt == 'h' ? EXIT_SUCCESS : EXIT_FAILURE);
		}
	}

	/* … */

	return EXIT_SUCCESS;
}
.Ed
.Sh SEE ALSO
.Xr mlib_setprogname 3 ,
.Xr optparse.h 3
.Sh AUTHORS
.An Thomas Voss Aq Mt mail@thomasvoss.com