如何编写使用GCC编译其他C程序的C程序? [英] How to write a C program that compiles other C programs using GCC?

查看:133
本文介绍了如何编写使用GCC编译其他C程序的C程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的程序做同样的事情作为终端命令如下:

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

这是我一直在尝试用:制作一个C程序进行编译另一

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

我就这么叫我的程序( ./PROGRAMNAME)的终端,它取代对我来说太键入 GCC需要,但需要我在休息太有型。

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.

推荐答案

您可以使用Linux和POSIX API的所以读首先高级Linux编程介绍(2)

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

您可以只运行与系统(3),您可以使用的snprintf(3)建命令字符串( code注射液的,但要注意);例如:

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);
   }
} 

顺便说一句,你的程序可能会产生一些C code,那么 + 的execve + waitpid函数 GCC 编译器(或制作),则甚至<一个HREF =htt​​p://man7.org/linux/man-pages/man3/dlopen.3.html相对=nofollow>的dlopen(3)编译的结果(你需要的gcc -fPIC -shared -O foo.c的-o foo.so 编译的dlopen 能够共享对象... )。 MELT 正在做这一点。 (所以做我的 manydl.c 这表明你可以做一个大的很多<$ C的$ C>的dlopen -s ...)

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

这篇关于如何编写使用GCC编译其他C程序的C程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆