如何使 CPP 文件对 ESP8266 Eclipse 项目中的链接器可见

How to make CPP files visible to linker in ESP8266 Eclipse project

Eclipse IDE 中有一个 "hello world" 项目应该针对 ESP8266 RTOS SDK 进行编译。

文件结构如下

我给它加了一个C++ class,放到它自己的文件夹里。这里是 class header

#ifndef MAIN_BLINKER_BLINKER_H_
#define MAIN_BLINKER_BLINKER_H_

class Blinker {
public:
  Blinker( int period );
  int Period() const;
private:
  int period_;
};

#endif /* MAIN_BLINKER_BLINKER_H_ */

和定义

#include "Blinker.h"

Blinker::Blinker( int period ) :
  period_( period )
{}

int Blinker::Period() const {
  return this->period_;
}

Main.cpp文件是这样的

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "blinker/Blinker.h"

extern "C" {

void app_main()
{
  auto blnk = Blinker( 3000 );
  int i = 0;
  while ( 1 ) {
    printf( "[%d] Hello beautiful world!\n", i );
    i++;
    vTaskDelay( blnk.Period() / portTICK_PERIOD_MS );
  }
}

}

它编译但在最后阶段失败,因为链接器(或应该是 xtensa 工具链中的链接器)没有看到 Blinker 方法的定义。这是我在构建日志中得到的

如果我将 class 文件放在 main.cpp 文件旁边,构建就会成功。但是随着时间的推移会有数百个文件,如果不进行任何分组,它很快就会变成一团乱麻。

或者我可以将此 class 放入 top-level components 文件夹并为其配备空 component.mk 文件。这也会使构建系统满意,但它会迫使我使用丑陋的 header 包含,如 ../components/blinker/Blinker.h,我想避免这种情况。

所以问题是如何让构建系统知道驻留在 main 文件夹的子文件夹中的 .c 和 .cpp 文件?

尝试将 blinker/Blinker.cpp 添加到您的 CMakeLists.txt
看一眼

您可以在“主”component.mk 文件中设置 COMPONENT_SRCDIRS

见: https://docs.espressif.com/projects/esp8266-rtos-sdk/en/latest/api-guides/build-system.html#example-component-makefiles