第一个文件是
/* OTHER.C */
#include <stdio.h>
#include <stdlib.h>
int i=35;
int fun1()
{
i++;
printf("%dn",i);
return 0;
}
int fun2()
{
i--;
printf("%dn",i);
return 0;
}
第二个文件是
/* MAIN.C */
#include <stdio.h>
#include "other.c"
int main()
{
printf("%dn",i);//WORKING FINE EVEN WITHOUT THE USE OF extern int i;
fun1();//working fine
fun2();//working fine
getch();
return 0;
}
在main.c
中的#include "other.c"
之后,变量i
以及fun1()
和fun2()
工作良好,即使没有在main.c
中将其声明为extern int i
、extern int fun1()
和extern int fun2()
。
但在像turbo c
这样的旧编译器中,它显示错误undeclared variable i
。
那么,这是C99
标准添加的附加功能吗?
#include
预处理器指令所做的是在#include
的位置实际物理地包含文件。
编译器本身处理所谓的翻译单元,这是预处理器在所有include和宏替换之后的输出。
所有这些都意味着编译器不会看到不同的文件,它只看到一个大文件,在您的情况下,它包含other.c
中的代码。
处理此类问题的通常方法是制作一个头文件,例如主文件将包含的other.h
,然后包含函数原型(声明)。然后,让构建系统生成两个对象文件,每个源文件一个,将对象文件链接到一个可执行文件中。
如果你使用gcc
,它可以很容易地这样做:
$ gcc main.c other.c -o myprogram
这告诉编译器将文件main.c
和other.c
编译为临时对象文件,然后将其链接在一起以创建myprogram
可执行文件。
为了实现这一点,您可能需要制作一个头文件,声明所需的东西:
/* OTHER.H */
#ifndef OTHER_H
#define OTHER_H
extern int i;
int fun1();
int fun2();
#endif
在main.c
文件#include
中,头文件而不是源文件。