其他分享
首页 > 其他分享> > c – Arduino的新运算符

c – Arduino的新运算符

作者:互联网

我被告知(特别是在an answer to C++ Standard Library on Arduino,以及Stack Overflow问题C++ string and Arduino String. How to combine them?))Arduino编译器没有实现new运算符.但是,我已经为使用它的Arduino(在Arduino IDE中)编写了一个程序,它运行得很好.

void setup() {
    Serial.begin(9600);
}

void loop() {
    char* array;
    char c;
    unsigned arraySize;

    Serial.write("Enter a 1 digit number.\n");

    do {
        c = Serial.read();
    } while(c < '0' or c > '9');
    arraySize = c-'0';

    Serial.write("You wrote ");
    Serial.write(c);
    Serial.write(".\n");
    Serial.write("Now enter ");
    Serial.write(c);
    Serial.write(" lower-case letters.\n");

    array = new char[arraySize];

    for (unsigned i = 0; i < arraySize;) {
        array[i] = Serial.read();
        if (array[i] >= 'a' and array[i] <= 'z')
            i++;
    }

    Serial.write("You entered: ");

    for (unsigned i = 0; i < arraySize; i++) {
        Serial.write(array[i]);
        Serial.write(" ");
    }
    Serial.write("\n");
}

以下是演示其功能的示例输出:

Enter a 1 digit number.
You wrote 5.
Now enter 5 lower-case letters.
You entered: h e l l o
Enter a 1 digit number.
You wrote 9.
Now enter 9 lower-case letters.
You entered: w a s s u p m a n
Enter a 1 digit number.
You wrote 9.
Now enter 9 lower-case letters.
You entered: h o w y a d o i n
Enter a 1 digit number.
You wrote 4.
Now enter 4 lower-case letters.
You entered: c o o l
Enter a 1 digit number.
You wrote 7.
Now enter 7 lower-case letters.
You entered: i t w o r k s
Enter a 1 digit number.

那么为什么我一直听到这个?这些人是错的,还是我只是误解了他们的意思?

解决方法:

new和delete被定义为Arduino发行版的一部分:
/usr/share/arduino/hardware/arduino/cores/arduino/new.h:

/* Header to define new/delete operators as they aren't provided by avr-gcc by default
   Taken from http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453 
 */
#ifndef NEW_H
#define NEW_H

#include <stdlib.h>

void * operator new(size_t size);
void operator delete(void * ptr); 

__extension__ typedef int __guard __attribute__((mode (__DI__)));

extern "C" int __cxa_guard_acquire(__guard *);
extern "C" void __cxa_guard_release (__guard *);
extern "C" void __cxa_guard_abort (__guard *); 

extern "C" void __cxa_pure_virtual(void);

#endif

new.h包含在Printable.h中,因此您可以在Arduino基本包含中获取它.但是这些运算符在AVR Libc中没有定义.我对这些设计选择的解释:Libc人认为这是一个坏主意,而Arduino人都是关于易用性:如果你想要新的和删除,请拥有它们.

标签:c,arduino,arduino-ide,new-operator
来源: https://codeday.me/bug/20191009/1877160.html