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.
11 * Note that this technique does not work in general for shared libaries,
12 * only for code compiled into a binary.
17 * // Distributed commandline option registration (note: ccan/opt is better!)
18 * #include <ccan/autodata/autodata.h>
21 * #include <stdbool.h>
24 * static bool verbose = false;
26 * // This would normally be in a header, so any C file can use it.
30 * bool (*cb)(char *optarg);
32 * AUTODATA_TYPE(options, struct option);
33 * #define REGISTER_OPTION(optstruct) \
34 * AUTODATA(options, (optstruct))
36 * // Now a few examples (could be anywhere in source)
37 * static bool verbose_cb(char *unused)
42 * static struct option dash_v = { 'v', false, verbose_cb };
43 * REGISTER_OPTION(&dash_v);
45 * static bool chdir_cb(char *dir)
48 * printf("chdir to %s. ", dir);
49 * if (chdir(dir) != 0)
53 * static struct option dash_C = { 'C', true, chdir_cb };
54 * REGISTER_OPTION(&dash_C);
56 * int main(int argc, char *argv[])
58 * struct option **opts;
61 * char *optstring, *p;
63 * // Gather together all the registered options.
64 * opts = autodata_get(options, &num);
66 * // Make pretty string for getopt().
67 * p = optstring = malloc(num * 2 + 1);
68 * for (i = 0; i < num; i++) {
69 * *(p++) = opts[i]->c;
70 * if (opts[i]->takes_arg)
75 * while ((o = getopt(argc, argv, optstring)) != -1) {
78 * // Call callback in matching option.
79 * for (i = 0; i < num; i++) {
80 * if (opts[i]->c == o) {
81 * if (!opts[i]->cb(optarg))
82 * err(1, "parsing -%c", o);
87 * // free up gathered option table.
88 * autodata_free(opts);
91 * printf("verbose mode on\n");
94 * // Given -v outputs 'verbose mode on'
95 * // Given -v -C / outputs 'chdir to /. verbose mode on'
97 int main(int argc, char *argv[])
99 /* Expect exactly one argument */
103 if (strcmp(argv[1], "depends") == 0) {
104 printf("ccan/compiler\n");
105 printf("ccan/ptr_valid\n");