/* * hello.c - A simple hello world program. */ #include #include #include "greeter.h" #define startswith(str, prefix) (!strncmp(str, prefix, strlen(prefix))) const char *description = "hello - A simple hello world program"; const char *usage = "Usage: hello \n" "Flags:\n" " --help|-h Print this message and exit\n" " --name=|-n The name being greeted"; int main(int argc, char *argv[]) { // Variables that get set by command line flags: char *name = "world"; // Loop over command line arguments: for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { print_help: printf("%s\n%s\n", description, usage); return 0; } else if (startswith(argv[i], "--name=")) { name = &argv[i][strlen("--name=")]; } else if (argv[i][0] == '-' && argv[i][1] != '-') { // Single-char flags: for (char *c = &argv[i][1]; *c; c++) { switch (*c) { case 'h': goto print_help; case 'n': name = (i+1 < argc) ? argv[++i] : ""; break; default: printf("Unknown flag: -%c\n%s\n", *c, usage); return 1; } } } else { printf("Unknown flag: %s\n%s\n", argv[i], usage); return 1; } } // Do the business logic: greet(name); return 0; }