简体   繁体   中英

How to write a C program that compiles other C programs using GCC?

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.

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 dlopen able 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 ...)

您可以使用exec系列函数,也可以使用system()方法直接执行shell命令

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM