怎么可能我的code正确编译没有必要的头? [英] How could my code compile correctly without necessary headers?

查看:70
本文介绍了怎么可能我的code正确编译没有必要的头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的功能fork()的,执行exec()...

但如何才能使这个程序,而不包括一些额外的头文件(比如SYS / types.h中,SYS / wait.h)编译。

我使用Ubuntu 10.04使用gcc 4.4.3版

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;诠释的main()
{
 将为pid_t PID; 的printf(分叉之前\\ n); PID =叉(); 如果(PID == 0)
 {
  /*儿童*/
  如果(execvp(./ CPUID,NULL))
  {
   的printf(错误。\\ n);
   出口(0);
  }
 }
 其他
 {
  如果(等待(NULL)!= -1)
  {
   的printf(OK \\ n);
  }
 } 返回0;
}


解决方案

在经典的ANSIC,如果你调用一个函数未声明的编译器的行为如同函数被隐式声明采取固定,但非特指的参数和返回数 INT 。所以,你的code行为,如果叉() execvp()因而被宣布:

  INT叉();
INT execvp();

由于 execvp()调用参数和返回 INT 固定号码,这个声明是兼容的。 叉()也需要的参数固定的数字,但回报率将为pid_t ;然而,由于将为pid_t INT 是大多数Linux架构等同类型,该声明被有效地兼容了。

这些函数的实际定义在C标准库,这是默认链接,所以定义可以在链接时,因此,code ++工程。

由于基思·汤普森指出,这种语言特性被丢弃在C语言标准的C99的版本,和C99或C11模式调用编译器必须至少发出时,一个函数被调用,而不显式声明的警告。

I use the functions fork(),exec()...

But how can this program be compiled without including some extra headers (like sys/types.h, sys/wait.h).

I use ubuntu 10.04 with gcc version 4.4.3

#include <stdio.h>
#include <stdlib.h>

int main()
{
 pid_t pid;

 printf("before fork\n");

 pid = fork();

 if(pid == 0)
 {
  /*child*/
  if(execvp("./cpuid", NULL))
  {
   printf("error\n");
   exit(0);
  }
 }
 else
 {
  if(wait(NULL) != -1)
  {
   printf("ok\n");
  }
 }

 return 0;
}

解决方案

In classic "ANSI" C, if you call a function without declaring it the compiler behaves as if the function was implicitly declared to take a fixed-but-unspecified number of arguments and return int. So your code acts as if fork() and execvp() were declared thus:

int fork();
int execvp();

Since execvp() takes a fixed number of arguments and returns int, this declaration is compatible. fork() also takes a fixed number of arguments, but returns pid_t; however since pid_t and int are equivalent types on most Linux architectures, this declaration is effectively compatible too.

The actual definitions of these functions are in the C standard library, which is linked by default, so the definition is available at link time and thus the code works.

As Keith Thompson notes, this language feature was dropped in the C99 revision of the C language standard, and compilers invoked in C99 or C11 mode must at least issue a warning when a function is called without being explicitly declared.

这篇关于怎么可能我的code正确编译没有必要的头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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