You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌入式C是否支持bool类型?AVR-GCC能否编译含bool的AVR MCU代码?

问题:AVR代码使用bool类型,能否在Linux下用avr-gcc编译?

我为AVR MCU编写了如下代码,用Arduino IDE编译上传后无报错且运行正常,但记得C语言不支持bool数据类型,请问该代码能否在Linux环境下通过avr-gcc编译?

//The following code is written for ATmega328P microcontroller
// Turns ON the led on a click of a switch and Turns OFF it again another click
#include <avr/io.h>
#include <avr/interrupt.h>

#define LED_PIN   PB5
#define SW_PIN    PD2

volatile bool ledOn = false;

// Function to initialize pinmode and interrupt
void init() {
 // Set LED pin as output
  DDRB = DDRB |(1 << DDB5);
  // Set switch pin as  pull-up resistor
  PORTD = PORTD |(1 << SW_PIN);
  // Enable interrupt on the switch pin
  EIMSK = EIMSK |(1 << INT0);
  // Trigger interrupt on failing edge of the switch signal
  EICRA = (1 << ISC01);
  // Enable global interrupts
  sei();
}

// Interrupt service routine for the switch
ISR(INT0_vect) {
  // If the switch is pressed, toggle the LED state
  if ((~PIND & (1 << SW_PIN)) && !ledOn) {
   PORTB = PORTB | (1 << LED_PIN);
    ledOn = true;
  }
  else{
  PORTB = PORTB & ~(1 << LED_PIN);
    ledOn = false;
  }

}

int main(void) {
 // Initialization
  init();

 // Loop forever
 while (1) {

    // NOP
  }

  return 0;
}

回答

直接用当前代码在Linux下用avr-gcc编译会报错,具体原因和解决方法如下:

  • 标准C在C99版本才引入_Bool原生类型,同时通过<stdbool.h>头文件提供bool作为_Bool的别名,以及true、false两个宏定义。
  • Arduino IDE能正常编译,是因为其核心库已经间接包含了<stdbool.h>,所以代码里不用显式包含也能识别bool、true、false。
  • 直接用avr-gcc编译时,代码未包含<stdbool.h>,编译器无法识别这些标识符,会抛出未定义的错误。

要让代码在Linux下通过avr-gcc编译,只需要在代码开头添加一行头文件包含:

#include <stdbool.h>

添加后,主流版本的avr-gcc(均支持C99及以上标准)就能正常编译该代码,功能和在Arduino IDE中运行的效果一致。


内容的提问来源于stack exchange,提问作者Jag Mohan Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:27:17