Using execvp

Sep 29, 2011 at 10:26pm
I need to use execvp to link together files that have been compiled by the program.

Up to 10 .o filenames are listed in a string array.
string compiledFiles[10];

This is my attempt to use the execvp to link the files.
execvp("gcc","gcc",compiledFiles,"-o","a.out");

If I need to post more of my code for a better understanding let me know! I think the problem is in those two lines.

Thanks!

Travis
Sep 29, 2011 at 11:38pm
closed account (S6k9GNh0)
Why not bash/powershell/batch?
Last edited on Sep 29, 2011 at 11:38pm
Sep 30, 2011 at 12:50am
The program is supposed to read a list of files, compile, and link. I've got the reading and compiling done, but it will not link.

The execvp command has the following syntax:

int execvp(const char *file, char *const argv[]);

I always end up with this error message:

proj1.cpp:82: error: cannot convert 'const char*' to 'char* const*' for argument '2' to 'int execvp(const char*, char* const*)'
Sep 30, 2011 at 2:55am
When the compiler complains that it cannot force the type of thing you are passing as argument to the type of thing it wants for argument, that is a strong clue that you are giving the function the wrong kind of thing.

The execv() functions expect an argument array. The way you appear to be trying to use it, you want to use the execlp() function. Don't forget also that the last argument must be NULL.

It is very important to pay attention to the man pages. You cannot just skim over them and wonder why things didn't work when you did things the way you thought they would work.
http://linux.die.net/man/3/execvp

1
2
  // Execute the GCC
  execlp( "gcc", "gcc", "main.o", "quux.o", "foo.o", NULL );

If you want to supply a variable selection of files to compile, you'll have to incorperate that into the argument list you give to execvp():

1
2
3
4
  // How exactly you create this list is up to you...
  char* args[] = { "gcc", "main.o", "quux.o", "foo.o", NULL };
  // Now execute it
  execvp( args[ 0 ], args );

I presume that you successfully called fork() before executing this function, right?
http://linux.die.net/man/2/fork


For all this grief, why don't you just use system() from your main program?
http://linux.die.net/man/3/system

Hope this helps.
Topic archived. No new replies allowed.