使用system()函数编译gcc

7

当我使用以下代码时,我的代码无法正确编译:

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

我收到了以下错误信息:

implicit declaration of function system

我不确定缺少什么,因为只有在调用gcc时才会抛出该系统错误。

这是我的代码:

#include <stdio.h>

int main() {
        ...
        system("gcc -o filename temp.c");
        return 0;
}

3
#include <stdio.h> 后添加 #include <stdlib.h>,这里是 system 函数的原型定义位置 - 参考链接:http://pubs.opengroup.org/onlinepubs/009695399/functions/system.html。 - Sean Bright
3个回答

10
main()的顶部添加#include <stdlib.h>
提示:当你看到内置函数的隐式声明时,你需要搜索该函数(例如现在应该用"C system()"进行搜索),以找到对应的标头,即函数声明的位置。其中一个结果应该是函数的参考链接。
在我们的例子中,是这个链接。在那里你可以看到:

SYNOPSIS

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

这段文字告诉你,如果你想使用system()函数,需要包含stdlib头文件。

正如Bright先生所指出的,如果你在类Unix操作系统上,可以使用man 3 system来了解更多信息。

示例:

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

2
如果你使用的是类Unix操作系统,那么man 3 system也可以解决问题。 - Sean Bright
好的,如果出现隐式函数声明错误,那么意味着缺少头文件吗? - Josh Buchanan
2
是的@JoshBuchanan,不是任何头文件,而是那个特定函数在该时刻需要包含的头文件。现在system()需要包含stdlib.h。不错的问题,你得到了我的+1。希望你记住我的提示,我相信它会有所帮助! - gsamaras
@G.Samaras 谢谢,我会记住的,这是我第三个C程序。仍在努力弄清楚何时查看和如何查看。 - Josh Buchanan

1

看起来您正在使用一个类Unix的系统,您应该知道 man 命令,它可以显示大多数库函数的文档。在我的系统上,当我输入:

$ man system

我得到:
SYSTEM(3)                  Linux Programmer's Manual                 

NAME
       system - execute a shell command

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

请注意,概述中告诉您需要使用的包含文件。手册页面还包括许多其他文档,如返回值。

-2

你没有遇到错误,也没有阻止代码的编译,只是一个警告,说明你没有添加库系统函数,但gcc会自动添加。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接