Aleister
Aleister

Reputation: 99

Making a C program to compile another

I'm looking to make a program with the purpose of compiling another. The purpose being using exec to run gcc. I have to use execve and what I have is:

#include <unistd.h>
#include <sys/types.h>

int main(int argc, char* argv[], char* envp[])
{
  argv[0] = "gcc";
  execve("/usr/bin/gcc" , argv, envp);
  return 0;
}

By doing

gcc -Wall p3p4.c -o run

It compiles without problems, but when doing

./run p3p1.c

To try and compile another one, this happens:

run: error trying to exec 'cc1': execvp: No such file or directory

EDIT:

As advised, when adding the line:

argv[0] = "gcc";

The program manages to work. Thank you for the input.

Upvotes: 1

Views: 1398

Answers (2)

Edouard Thiel
Edouard Thiel

Reputation: 6208

excve tells you that he didn't find gcc. Try

execvpe ("gcc", argv, envp);

Note that here envp is useless (and not POSIX) ; you can safely remove envp from main() and call

execvp ("gcc", argv);

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

Try setting argv[0] like a well-behaved program:

argv[0] = "gcc";
execve("/usr/bin/gcc" , argv, envp);

run: error trying to exec 'cc1':

This is apparently what gcc tries to run when it finds something unexpected in argv[0].

Upvotes: 3

Related Questions