如何修复 Arduino / PlatformIO 对 `loop()` 的未定义引用

问题:

尝试编译 Arduino 或 PlatformIO 项目时,你看到类似这样的错误消息

linker_error_ld.txt
/home/uli/.platformio/packages/[email protected]+2021r2-patch5/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld: .pio/build/esp32dev/libFrameworkArduino.a(main.cpp.o):(.literal._Z8loopTaskPv+0x8): undefined reference to `loop()'

解决方案

你还没有在源代码中声明 loop() 函数。打开 main.cpp 或你的 .ino 源代码文件,从以下(空)loop() 函数开始,它什么也不做:

empty_loop_example.cpp
void loop() {
    // Nothing to do here since HTTPServer
    // is running in a separate thread
    delay(1000);
}

在源代码中添加任何 void loop() { /* ... */} 函数后,再次尝试构建/上传,错误消息应该消失了。

如果需要,你还可以添加代码,例如每次循环运行时向串口打印消息:

loop_with_serial_example.cpp
void loop() {
    // Nothing to do here since HTTPServer
    // is running in a separate thread
    Serial.println("Hello world!");
    delay(1000);
}

Check out similar posts by category: Arduino, C/C++, PlatformIO