6 * autodata - stash pointers in your binary for automatic registration
8 * This code allows declarations in your source which you can gather
9 * together at runtime to form tables. This is often used in place of
10 * having a central registration function or table.
12 * Note that this technique does not work in general for shared libaries,
13 * only for code compiled into a binary.
18 * // Distributed commandline option registration (note: ccan/opt is better!)
19 * #include <ccan/autodata/autodata.h>
22 * #include <stdbool.h>
25 * static bool verbose = false;
27 * // This would normally be in a header, so any C file can use it.
31 * bool (*cb)(char *optarg);
33 * AUTODATA_TYPE(options, struct option);
34 * #define REGISTER_OPTION(optstruct) \
35 * AUTODATA(options, (optstruct))
37 * // Now a few examples (could be anywhere in source)
38 * static bool verbose_cb(char *unused)
43 * static struct option dash_v = { 'v', false, verbose_cb };
44 * REGISTER_OPTION(&dash_v);
46 * static bool chdir_cb(char *dir)
49 * printf("chdir to %s. ", dir);
50 * if (chdir(dir) != 0)
54 * static struct option dash_C = { 'C', true, chdir_cb };
55 * REGISTER_OPTION(&dash_C);
57 * int main(int argc, char *argv[])
59 * struct option **opts;
62 * char *optstring, *p;
64 * // Gather together all the registered options.
65 * opts = autodata_get(options, &num);
67 * // Make pretty string for getopt().
68 * p = optstring = malloc(num * 2 + 1);
69 * for (i = 0; i < num; i++) {
70 * *(p++) = opts[i]->c;
71 * if (opts[i]->takes_arg)
76 * while ((o = getopt(argc, argv, optstring)) != -1) {
79 * // Call callback in matching option.
80 * for (i = 0; i < num; i++) {
81 * if (opts[i]->c == o) {
82 * if (!opts[i]->cb(optarg))
83 * err(1, "parsing -%c", o);
88 * // free up gathered option table.
89 * autodata_free(opts);
92 * printf("verbose mode on\n");
95 * // Given "-v" outputs "verbose mode on\n"
96 * // Given "-v -C /" outputs "chdir to /. verbose mode on\n"
98 int main(int argc, char *argv[])
100 /* Expect exactly one argument */
104 if (strcmp(argv[1], "depends") == 0) {
105 printf("ccan/compiler\n");
106 printf("ccan/ptr_valid\n");