pull in getopt; add -o argument to specify output file name

This commit is contained in:
Josh Holtrop 2018-05-20 16:45:43 -04:00
parent 46145fa975
commit 23a92ca9bd
2 changed files with 52 additions and 4 deletions

View File

@ -6,6 +6,7 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include <getopt.h>
static char preprocessed_fname[] = "/tmp/cxlppXXXXXX"; static char preprocessed_fname[] = "/tmp/cxlppXXXXXX";
static char c_fname[] = "/tmp/cxlcXXXXXX.c"; static char c_fname[] = "/tmp/cxlcXXXXXX.c";
@ -88,7 +89,7 @@ bool emit_c(Node * node)
return true; return true;
} }
bool compile() bool compile(const char * output_fname)
{ {
pid_t pid = fork(); pid_t pid = fork();
if (pid < 0) if (pid < 0)
@ -98,7 +99,7 @@ bool compile()
} }
else if (pid == 0) 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 else
{ {
@ -107,9 +108,55 @@ bool compile()
return true; 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[]) 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) if (preprocess_successful)
{ {
Node * node = parse(preprocessed_fname); Node * node = parse(preprocessed_fname);
@ -117,7 +164,7 @@ int main(int argc, char * argv[])
{ {
if (emit_c(node)) if (emit_c(node))
{ {
compile(); compile(output_fname);
} }
} }
} }

View File

@ -7,6 +7,7 @@ def options(opt):
def configure(conf): def configure(conf):
conf.load("compiler_c compiler_cxx flex bison"); conf.load("compiler_c compiler_cxx flex bison");
conf.check(header_name = "getopt.h", global_define = False)
def build(bld): def build(bld):
bld.load("compiler_c compiler_cxx flex bison"); bld.load("compiler_c compiler_cxx flex bison");