0

I want my program to do the same thing as the terminal commands below:

gcc program1.c -o p1 funcs.c

gcc program2.c -o p1 funcs.c

This is what I've been experimenting with: Making a C program to compile another

I got as far so calling my program (./"programName") in the terminal that it replaced the need for me too type gcc but needing me too type in the rest.

Community
  • 1
  • 1

3 Answers3

3

You can use the Linux and POSIX APIs so read first Advanced Linux Programming and intro(2)

You could just run a compilation command with system(3), you can use snprintf(3) to build the command string (but beware of code injection); for example

void compile_program_by_number (int i) {
   assert (i>0);
   char cmdbuf[64];
   memset(cmdbuf, 0, sizeof(cmdbuf));
   if (snprintf(cmdbuf, sizeof(cmdbuf),
               "gcc -Wall -g -O program%d.c fun.c -o p%d",
               i, i) 
         >= sizeof(cmdbuf)) {
       fprintf(stderr, "too wide command for #%d\n", i);
       exit(EXIT_FAILURE);
   };
   fflush(NULL); // always useful before system(3)
   int nok = system(cmdbuf);
   if (nok) {
      fprintf(stderr, "compilation %s failed with %d\n", cmdbuf, nok);
      exit(EXIT_FAILURE);
   }
} 

BTW, your program could generate some C code, then fork + execve + waitpid the gcc compiler (or make), then perhaps even dlopen(3) the result of the compilation (you'll need gcc -fPIC -shared -O foo.c -o foo.so to compile a dlopenable shared object...). MELT is doing exactly that. (and so does my manydl.c which shows that you can do a big lot of dlopen-s ...)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

You can use exec family function or you can directly execute shell command by using system() method

Abhi
  • 724
  • 1
  • 6
  • 15
0

There is build in functionality in Makefile.

All you would have to call is make.

How to: http://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/

Great stackoverflow question: How do I make a simple makefile for gcc on Linux?

Community
  • 1
  • 1
Hashman
  • 151
  • 5