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

北城余情 提交于 2020-01-07 09:04:09

问题


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.


回答1:


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




回答2:


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




回答3:


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?



来源:https://stackoverflow.com/questions/26001699/how-to-write-a-c-program-that-compiles-other-c-programs-using-gcc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!