为什么要用到extern 声明 include所包含的程序中的函数?

来源:互联网 发布:阿里云跟阿里巴巴 编辑:程序博客网 时间:2024/05/22 10:30
为什么要用到extern 声明 include所包含的程序中的函数?

在头文件中声明函数时,前面的extern可有可无,只要这些函数曾在某个.c文件中实现就行了,不过一些函数没有在所包含的头文件中给出声明,同时函数的定义位于其它文件中,这时候使用该函数的.c文件必须用extern标记该函数为外部函数。举个例子:
/* c.h */
extern int max(int a, int b);
extern int min(int a, int b);

/* a.c */
#include <stdio.h>
/* 这里需要明确指定output为extern函数 */
extern void output();
int max(int a, int b)
{
return (a > b ? a : b);
}
int min(int a, int b)
{
return (a < b ? a : b);
}
void main()
{
output();
}

/* b.c */
#include "c.h"

void output()
{
printf("%d %d\n", max(10, 5), min(10, 5));
}


---------------main.cpp
extern void output(); //这里调用这里声明
extern a; //这里调用这里声明 ,,  都可以放在一个头文件中,然后调用

#include<stdio.h>
void main()
{
    output();
    printf("%d\n",a);
}
---------------a.cpp

}#include<stdio.h>


int a =12;


void output()
{
printf("void \n");

}
原创粉丝点击