From 23a92ca9bd8780101b7bb42a567bb54a2892815e Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Sun, 20 May 2018 16:45:43 -0400 Subject: [PATCH] pull in getopt; add -o argument to specify output file name --- src/main.cc | 55 +++++++++++++++++++++++++++++++++++++++++++++++++---- wscript | 1 + 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/main.cc b/src/main.cc index 2863ef8..358ab68 100644 --- a/src/main.cc +++ b/src/main.cc @@ -6,6 +6,7 @@ #include #include #include +#include static char preprocessed_fname[] = "/tmp/cxlppXXXXXX"; static char c_fname[] = "/tmp/cxlcXXXXXX.c"; @@ -88,7 +89,7 @@ bool emit_c(Node * node) return true; } -bool compile() +bool compile(const char * output_fname) { pid_t pid = fork(); if (pid < 0) @@ -98,7 +99,7 @@ bool compile() } else if (pid == 0) { - execlp("gcc", "gcc", "-c", c_fname, "-o", "out.o", NULL); + execlp("gcc", "gcc", "-c", c_fname, "-o", output_fname, NULL); } else { @@ -107,9 +108,55 @@ bool compile() return true; } +std::string g_output_fname; +const char * build_output_fname(const char * input_fname) +{ + g_output_fname = input_fname; + size_t pos = g_output_fname.rfind("."); + if (pos != std::string::npos) + { + g_output_fname.replace(pos, g_output_fname.size() - pos, ".o"); + } + else + { + g_output_fname += ".o"; + } + return g_output_fname.c_str(); +} + int main(int argc, char * argv[]) { - bool preprocess_successful = preprocess(argv[1]); + int opt; + int option_index; + const char * output_fname = nullptr; + + static const struct option long_options[] = { + { NULL, 0, NULL, 0 }, + }; + + while ((opt = getopt_long(argc, argv, "o:", long_options, &option_index)) != -1) + { + switch (opt) + { + case 'o': + output_fname = optarg; + break; + } + } + + if (optind >= argc) + { + return -2; + } + + const char * input_fname = argv[optind]; + + if (output_fname == nullptr) + { + output_fname = build_output_fname(input_fname); + } + + bool preprocess_successful = preprocess(input_fname); if (preprocess_successful) { Node * node = parse(preprocessed_fname); @@ -117,7 +164,7 @@ int main(int argc, char * argv[]) { if (emit_c(node)) { - compile(); + compile(output_fname); } } } diff --git a/wscript b/wscript index 142a301..610e0a7 100644 --- a/wscript +++ b/wscript @@ -7,6 +7,7 @@ def options(opt): def configure(conf): conf.load("compiler_c compiler_cxx flex bison"); + conf.check(header_name = "getopt.h", global_define = False) def build(bld): bld.load("compiler_c compiler_cxx flex bison");