Skip to content

Instantly share code, notes, and snippets.

@gipert
Last active August 18, 2020 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gipert/3f91d6dc8bf31818cff163faeb18f38e to your computer and use it in GitHub Desktop.
Save gipert/3f91d6dc8bf31818cff163faeb18f38e to your computer and use it in GitHub Desktop.
Template ROOT macro that can be executed directly with command-line arguments
//usr/bin/env root -l ${0}\(\""${0}"\",\""${*}"\"\); exit $?
/* ROOTmacro_cmdline_args.C
*
* template ROOT macro that can be executed (do not forget to
* `chmod +x`) with command-line arguments
*
* Author: Luigi Pertoldi - pertoldi@pd.infn.it
* Created: Sun 24 Mar 2019
*/
#include <getopt.h>
void usage() {
std::cerr << "\n"
<< "USAGE: <progname> [options] [ROOTfile:objname]\n"
<< "\n"
<< "options:\n"
<< " --help|-h : print this help message and exit\n"
<< " ..."
<< "\n";
gSystem->Exit(1);
}
void ROOTmacro_cmdline_args(std::string prog = "ROOTmacro_cmdline_args", std::string args = "") {
// this is for getopt to work
args = prog + " " + args;
int argc = 0;
char** argv = new char*[200];
// get all arguments
std::istringstream iss(args);
std::string word;
while (iss >> word) {
char* tmp = new char[200];
strcpy(tmp, word.c_str());
argv[argc] = tmp;
argc++;
}
const char* const short_opts = ":h";
const option long_opts[] = {
{ "help", no_argument, nullptr, 'h' },
// add other options...
{ nullptr, no_argument, nullptr, 0 }
};
// read in with getopt
int opt = 0;
while ((opt = getopt_long(argc, argv, short_opts, long_opts, nullptr)) != -1) {
switch (opt) {
// ...
case 'h': // -h or --help
case '?': // Unrecognized option
default:
usage();
}
}
// get extra arguments
std::vector<std::string> extra_args;
for(; optind < argc; optind++){
extra_args.emplace_back(argv[optind]);
}
if (!extra_args.empty()) {
// ...
}
// get script location
auto script_dir = prog.substr(0, prog.find_last_of('/'));
return;
}
// vim: filetype=cpp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment