ccompilationbinary

Build new binary from C program


I'm working on a C program, it's a custom shell that asks the user to set different options (IP, port, ...) and then allow the user to build a binary based on these informations. I was wondering what is the best way to build a new binary from within an existing program ?

EDIT: My question may have been a bit unclear. The new compiled binary is a simple TCP client that will connect to the specified IP and Port. I don't want this new binary to be dependant of a config file. How can i build this from my existing C program ? Should i write the IP and Port to a .c file and then compile it using system("/bin/gcc ...") ?


Solution

  • I think you are describing code generation and programmatically compiling a new executable. There are many ways to do what you have described. Here is a very simple (and very rough draft of a) set of steps to code gen, and compile:

    1) Use printf, fgets calls from existing program to prompt user for a specific set of input values
    2) Convert command line numeric input values if necessary. (Using atoi(), or strtod() for example)
    3) Open a file for write, (eg FILE *fp = fopen(filespec, "w");)
    4) Using fputs(), send a series of lines to the file comprised of a C source file, including values from steps 1&2 from the user input.
    eg. fputs("#include _some file_", fp); (and other header files as needed)
    eg, fputs("int main(int argc, char *argv[]) {", fp);
    fputs(...) (all of the rest of your lines to make up the complete user defined code.)
    fputs("return 0; }", fp);
    5) close the file: fclose(fp);
    6) Construct a gcc command line compile string to be used on command line on the file you just created.
    7) Using popen() (If available) or system() or if using Windows, something like this to send a command to the OS, to execute gcc (or other compiler) on the command line to create your executable.