【问题标题】:Implicit declaration of function and conflicting type - AVR函数和冲突类型的隐式声明 - AVR
【发布时间】:2015-06-02 06:41:50
【问题描述】:

这是我的第一个 AVR 程序。在构建时,代码显示错误: “编码”的冲突类型 'Encode' 的隐式声明

我写了以下代码:

#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>

#define SegDataPort PORTC
#define SegDataPin PINC
#define SegDataDDR DDRC

#define SegCntrlPort PORTD
#define SegCntrlPin PIND
#define SegCntrlDDR DDRD

int main(void)
{
   SegDataDDR = 0xFF;
   SegCntrlDDR = 0xF3;
   SegCntrlPort = 0xF3;
   SegDataPort = 0x00;
   unsigned char adc_value;
   float volt = adc_value/1023;
   int temp = floor(volt*10 + 0.5);

   SegDataPort = Encode(temp1%10);

   //^^^^ implicit declaration of 'Encode' 

   SegCntrlPort = ~0x01;
   SegDataPort = Encode((temp1/10)%10);
   SegCntrlPort = ~0x02;
   SegDataPort = Encode(temp1/100);
   SegCntrlPort = ~0x04;
}

unsigned char Encode(int digit)
{
   unsigned char val;
   switch(digit)
   {
      case 0 : Val = 0b00111111;
      case 1 : val = 0b00000110;

      /// so on till case 9
   }
   return val;
}

我使用 ATmega16 作为微控制器。我还添加了更多的库,例如用于地板函数的数学等。我尝试将 int 更改为 unsigned int、unsigned char 等,但它仍然无法正常工作并显示相同的错误。 请帮帮我。

【问题讨论】:

  • @mathematician1975 AFAIK,PORTx 是 AVR 特定的寄存器,可以用作普通的 c 变量。如果我错了,请纠正我。

标签: c++ c compiler-errors avr atmega16


【解决方案1】:

“编码”的隐式声明

C 中,函数需要在使用(调用)之前声明定义

要么

  • Encode()函数的定义移到main()之前
  • main() 之前向Encode() 添加前向声明。

也就是说,floor() 是一个函数,在math.h 中定义,在math 库中定义。要使用它,您需要在编译时 #include &lt;math.h&gt; 并与 -lm 链接。


关于这里使用的程序逻辑,

unsigned char adc_value;
float volt = adc_value/1023;
int temp = floor(volt*10 + 0.5);

问题很大,因为

  1. adc_value 未初始化使用,导致undefined behaviour
  2. adc_value 的类型为 char。将它除以 1023 的值将始终得到 0 的结果,因为除法将作为 整数除法 进行,并且不会产生 @987654339 @result 本身,正如你所预料的那样。

我的建议,把那个代码块改成

int adc_value = <some value to initialize>;  //or some input function
float volt = (float)adc_value/1023;          //enforce floating point division
int temp = floor(volt*10 + 0.5);

【讨论】:

  • 成功了。谢谢你。但是你能告诉我为什么之前必须在 C 中调用该函数吗?因为 C++、Java 或 Python 并非如此
  • @Yash 之前打过电话吗?不,这是另一种方式,它必须在调用之前声明。您可以查看here 了解更多信息。
【解决方案2】:

第一个错误:

 unsigned char adc_value;
 float volt = adc_value/1023;

您将adc_value 定义为unsigned char,并在下一行中尝试将其除以1023,并将结果分配给float 类型变量。你不能用C 语言做这些。 (更何况你没有为adc_value分配任何值!它将是零或随机值)

第二个错误:

您的第二个问题是您在main() 中调用它之后定义了您的Encode 函数。您必须将整个函数移到 main() 函数之前,或者只是将其原型添加到 main() 函数之前。

即在main()之前添加unsigned char Encode(int digit);

口渴错误:

您尝试为使用#define 声明的变量分配一些值:

#define SegDataPort PORTC
#define SegDataPin PINC
#define SegDataDDR DDRC

#define SegCntrlPort PORTD
#define SegCntrlPin PIND
#define SegCntrlDDR DDRD

int main(void)
{
   SegDataDDR = 0xFF;
   SegCntrlDDR = 0xF3;
   SegCntrlPort = 0xF3;
   SegDataPort = 0x00;
   .
   .
   .

这也是违法的。那些用#define 定义的变量是常数,你不能试图在程序体中改变它们。

【讨论】:

  • adc_value 是我的模拟输入。所以,它的范围从 0 到 1023。
  • 恕我直言,您介意再检查一下您的第三点吗?
  • 我不太确定,没有 AVR 的经验。请验证一次this
  • @Yash 它定义为unsigned char,因此它的值可以从0255。 (它有 8 位长度。)为什么你没有将它定义为 int
  • 那么,我怎么能说我的微控制器的端口是输入或输出。我在冲浪时只发现了这种方式。
最近更新 更多