Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiling with gcc with system()

My code does not compile right when I use:

system("gcc -o filename temp.c");

I am getting:

implicit declaration of function system

I'm not sure what is missing, because it only throws the system error on the gcc call.

Here is my code:

#include <stdio.h>

int main() {
        ...
        system("gcc -o filename temp.c");
        return 0;
}
like image 646
Josh Buchanan Avatar asked Apr 07 '15 22:04

Josh Buchanan


2 Answers

Add #include <stdlib.h> at the top of main().

Tip: When you see implicit declaration of a built-in function, you have to search for the function (with google, for example now you should have searched with "system() C"), in order to find the corresponding header, i.e. where the function is declared. Then one of the results should be the ref of the function.

In our case this link. There you can see:

SYNOPSIS

#include <stdlib.h>
int system(const char *command);

which tells you that you have to include stdlib header to use system().

As Mr. Bright noticed, if you're on on a inux-like OS, man 3 system should do the trick too.

Example:

samaras@samaras-A15:~$ man 3 system
SYSTEM(3)                  Linux Programmer's Manual                 SYSTEM(3)

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>  <-- this is what we are looking for!

       int system(const char *command);
...
like image 139
gsamaras Avatar answered Oct 24 '22 04:10

gsamaras


Since it appears you are using a Posix system, you should know about the man command which shows documentation for most library calls. On my system, when I type:

$ man system

I get:

SYSTEM(3)                  Linux Programmer's Manual                 

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

Notice that in the synopsis it tells you the include file you need to use. The man page also includes a lot of other documentation such as the return value.

like image 24
R Samuel Klatchko Avatar answered Oct 24 '22 05:10

R Samuel Klatchko