main.cpp.tmpl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "h.h"
  5. void pexit(int code) {
  6. printf("Exit with code %d.\n", code);
  7. hlogi("Exit with code %d.", code);
  8. exit(code);
  9. }
  10. typedef struct arg_s {
  11. string cmd;
  12. string conf; // -c
  13. } arg_t ;
  14. arg_t g_arg;
  15. const char* options = "hvc:";
  16. const char* options_descr = "Options:\n\
  17. -h Print help\n\
  18. -v Print version\n\
  19. -c conffile Configure file\n\
  20. ";
  21. string version() {
  22. return asprintf("%s version %s", g_arg.cmd.c_str(), get_compile_version());
  23. }
  24. string usage() {
  25. return asprintf("Usage: %s [%s]", g_arg.cmd.c_str(), options);
  26. }
  27. void print_help() {
  28. puts(usage().c_str());
  29. puts(options_descr);
  30. puts(version().c_str());
  31. }
  32. bool parse_command_line(int argc, char** argv) {
  33. int opt = -1;
  34. while ((opt = getopt(argc, argv, options)) != -1) {
  35. switch (opt) {
  36. case 'h': {
  37. print_help();
  38. pexit(0);
  39. }
  40. break;
  41. case 'v': {
  42. puts(version().c_str());
  43. pexit(0);
  44. }
  45. break;
  46. case 'c': {
  47. g_arg.conf = optarg;
  48. }
  49. break;
  50. default: {
  51. return false;
  52. }
  53. break;
  54. }
  55. }
  56. return true;
  57. }
  58. int main(int argc, char** argv) {
  59. string strCmd((const char*)argv[0]);
  60. g_arg.cmd = filename(strCmd);
  61. string strLog = g_arg.cmd + ".log";
  62. hlog_set_file(strLog.c_str());
  63. hlog_set_level(LOG_LEVEL_INFO);
  64. hlogi("%s", version().c_str());
  65. if (!parse_command_line(argc, argv)) {
  66. printf("Command line parse error, please use -h to get help.\n");
  67. pexit(-10);
  68. }
  69. // ...
  70. pexit(0);
  71. }