5 * autodata - stash pointers in your binary for automatic registration
7 * This code allows declarations in your source which you can gather
8 * together at runtime to form tables. This is often used in place of
9 * having a central registration function or table.
14 * // Distributed commandline option registration (note: ccan/opt is better!)
15 * #include <ccan/autodata/autodata.h>
18 * #include <stdbool.h>
21 * static bool verbose = false;
23 * // This would normally be in a header, so any C file can use it.
27 * bool (*cb)(char *optarg);
29 * AUTODATA_TYPE(options, struct option);
30 * #define REGISTER_OPTION(optstruct) \
31 * AUTODATA(options, (optstruct))
33 * // Now a few examples (could be anywhere in source)
34 * static bool verbose_cb(char *unused)
39 * static struct option dash_v = { 'v', false, verbose_cb };
40 * REGISTER_OPTION(&dash_v);
42 * static bool chdir_cb(char *dir)
45 * printf("chdir to %s. ", dir);
46 * if (chdir(dir) != 0)
50 * static struct option dash_C = { 'C', true, chdir_cb };
51 * REGISTER_OPTION(&dash_C);
53 * int main(int argc, char *argv[])
55 * struct option **opts;
58 * char *optstring, *p;
60 * // Gather together all the registered options.
61 * opts = autodata_get(options, &num);
63 * // Make pretty string for getopt().
64 * p = optstring = malloc(num * 2 + 1);
65 * for (i = 0; i < num; i++) {
66 * *(p++) = opts[i]->c;
67 * if (opts[i]->takes_arg)
72 * while ((o = getopt(argc, argv, optstring)) != -1) {
75 * // Call callback in matching option.
76 * for (i = 0; i < num; i++) {
77 * if (opts[i]->c == o) {
78 * if (!opts[i]->cb(optarg))
79 * err(1, "parsing -%c", o);
84 * // free up gathered option table.
85 * autodata_free(opts);
88 * printf("verbose mode on\n");
91 * // Given -v outputs 'verbose mode on'
92 * // Given -v -C / outputs 'chdir to /. verbose mode on'
94 int main(int argc, char *argv[])
96 /* Expect exactly one argument */
100 if (strcmp(argv[1], "depends") == 0) {
101 printf("ccan/compiler\n");
102 printf("ccan/ptr_valid\n");