Compiler directives cannot disable #incldue statement?

I’m going to develop a library for both ESP8266 & ESP32, and I use PlatformIO in vscode.

In my project, there has some include libraries which only work for ESP8266, I have added the compiler directives to control the include library. It works fine on ESP8266 path, but when I change the environment for ESP32, it will cause error until I comment out the #include statement for ESP8266.

I have tested again and again, and I can find that it has problem even for a very simple dummy sketch as below,

#if defined(ESP8266)
    #include <SoftwareSerial.h>

void setup() {
    // put your setup code here, to run once:

void loop() {
    // put your main code here, to run repeatedly:

The sketch will do nothing and just include the SoftwareSerial library for ESP8266. However, it still cause the error of gpio.h not found as the gpio.h is available for ESP8266 only, and it has been used in the SoftwareSerial library, but it should not be included for ESP32 board. It works only if I comment out the #include line.

There has no problem if I compile the sketch in Arduino IDE for both ESP8266 & ESP32 board.

I guessed this may be the issue as this is a multi-environment project controlled by the evn_default setting in platformio.ini. So I tried to changed the platformio.ini and make this a single environment project for ESP32, but keep the include statement for ESP8266, it will still compile the include library.

I have also tried to install the library or just paste the library in lib folder, it has the same result. If I completely remove the library, it works fine, it will not tell anything missing. However, in my situation, I need the library for ESP8266, it’s not a good choice to remove the library or comment out the line when compiling for ESP32.

Does it mean that the compiler with PlatformIO will still try to compile the library even it’s is not used in current environment setting?

Please set LDF mode to chain+ via Library Dependency Finder (LDF) — PlatformIO latest documentation

Thanks a lot. It works by setting LDF mode to chain+.