读书人

多文件工程中怎样调用外部函数?解决

发布时间: 2012-02-19 19:43:39 作者: rapoo

多文件工程中,怎样调用外部函数?
我刚刚接触调用外部函数,不是太懂,手头又没有这方面系统讲解的资料,我的一个工程中包含了三个文件,分别为Main.c, RTC.c , Temper.c ,我要在Main 中的mian()函数中调用后两个文件的函数。该如何操作?

我自己试着编的程序,如下,调试发现五个WARING, 2个ERROR,意思是重复定义了两个外部函数。明白人帮我看看是 怎么回事吧,看看我的外部变量和函数声明的对吗?
//main.c
#include <C8051F020.h>
#include "RTC.c "
#include "Temper.c "

#include <math.h>
#include <intrins.h>
#include <absacc.h>

void Oscillator_Init()
{
int i = 0;
OSCXCN = 0x67;
for (i = 0; i < 3000; i++){WDTCN=0xa5;}; // Wait 1ms for initialization
while ((OSCXCN & 0x80) == 0);
OSCICN = 0x88;
}

void main(void)
{
extern uchar second;
extern uchar ptTemper[4],ptTemp_Average[4]; /*声明外部变量*/
extern void ReadRTC();
extern void WriteRTC(uchar Year,uchar Month,uchar Day,uchar Hour,uchar Minute,uchar Second);
extern void Delay1s();
extern Read_Temperature(uchar *ptTemp,uchar n);
extern Temp_Con(uchar *ptTemp_Avr); /*声明外部函数*/
EA=0;
WDTCN=0xde;
WDTCN=0xad;//禁止看门狗
Oscillator_Init();

//I/O 初始化
P1MODE=0xff;
PRT1CF=0x00;

P1=0xe5;

PRT2CF &=0x7f;
P2MODE |=0x0c;
P2|=0x0c;

WriteRTC(0,0,0,0,0,0); //Initialize RTC
Delay1s();

do{

ReadRTC();
if (second==8)
{
Read_Temperature(ptTemper,1);

Read_Temperature(ptTemper,2);

Temp_Con(ptTemp_Average);
}

} while (1);

}



调试错误:

COPYRIGHT KEIL ELEKTRONIK GmbH 1987 - 2004
*** WARNING C235 IN LINE 27 OF MAIN.C: parameter 2: different types
*** WARNING C235 IN LINE 27 OF MAIN.C: parameter 3: different types
*** WARNING C235 IN LINE 27 OF MAIN.C: parameter 4: different types
*** WARNING C235 IN LINE 27 OF MAIN.C: parameter 5: different types
*** WARNING C235 IN LINE 27 OF MAIN.C: parameter 6: different types
*** ERROR C231 IN LINE 29 OF MAIN.C: '_Read_Temperature ': redefinition
*** ERROR C231 IN LINE 30 OF MAIN.C: '_Temp_Con ': redefinition

C51 COMPILATION COMPLETE. 5 WARNING(S), 2 ERROR(S)



[解决办法]
在同一个工程中,不同文件只要调用非本文件里的函数(就算是在本文件里的函数,在定义前调用)必须先声明.具体你可以在文件开始处声明,也可以将声明写入相应的头文件然后用头文件包含将其加入.

外部的声名应用关键字:extern

具体你可以看看C语言里对这个关键字的讲述.
[解决办法]
#include "RTC.c "
#include "Temper.c "

头文件包含只能包含,.H或HPP文件


[解决办法]

我用gcc编译同LZ类似的例子是可以的:
//Function multiply() defined in file1.c, sum() defined in file2.c
#include <stdio.h>
#include "file1.c "
#include "file2.c "
int main()
{
extern int multiply();
extern int sum();

int a, b;
int result;

printf( "Please input a and b(Format:a,b): ");
scanf( "%d, %d ", &a, &b);
result = multiply(a, b);
printf( "The result of multiply is: %d\n ", result);
result = sum(a, b);
printf( "The result of sum is: %d\n ", result);

return 0;
}
但是我注析掉
//#include "file1.c "
//#include "file2.c "
后就会提示出错信息:undefined reference multiply and sum.
-------
鉴于不同的编译器会出现不一样的结果,
include *.c 是不规范,可以注析掉试试,
还有,可以在 "RTC.c "和 "Temper.c "里被其他文件调用的函数加上 extern。
编译器提示“redefinition”,也可以只注析掉
// extern Read_Temperature(uchar *ptTemp,uchar n);
// extern Temp_Con(uchar *ptTemp_Avr);
这两句试试。
[解决办法]
用extern声明后再使用。

读书人网 >单片机

热点推荐