PlatformIO in VSCODE for Arduino and ESP32 - External source files help please

I’m new to PlatformIO.
My project so far consists of main.cpp and several libraries I have installed using Library tool in PlatformIO. My target device is ESP32 so the main code has a combination of C++ and C code.

Now I want to refactor my code and split out some functions into other source files but having trouble getting access to referenced items. The first one is for the Serial2 port.
I created serial.h file and serial.c file as below. Problem is the red squiggly under “Serial2” with error that it is undefined.

What do I need to fix this please? Also, do I need to add any text in workspace file under files.associations?

#ifndef _serial_h_h

#define serial.h

#define RX_PIN 17

#define TX_PIN 16

void serial_init(void);

#endif

And serial.c code as below
#include <Arduino.h>
#include “serial.h”

serial_init()

{

Serial2.begin(115200,SERIAL_8N1,RX_PIN,TX_PIN);

}

What? There’s a funadamental misunderstanding here. You’re trying to directly reference C++ classes in C code, that won’t work. Arduino is a C++ framework, C has no notion of classes. You can’t just #include <Arduino.h> in a .c file and start using C++ classes that Arduino defines.

You can call into C++ code in C with special wrappers (here, here), but it’s like deliberately stabbing yourself.

As a start, you would have to add CPP file in your project like arduino_c_wrappers.cpp

#include "arduino_c_wrapper.h"
#include <Arduino.h>

void Serial2_begin(int baud, int format, int rx, int tx) {
   Serial2.begin(baud, format, rx, tx);
}

with arduino_c_wrapper.h

#pragma once

#ifdef __cplusplus
extern "C" {
#endif

void Serial2_begin(int baud, int format, int rx, int tx);

#ifdef __cplusplus
}
#endif

With this, you create a function with C linkage (extern "C", mind the name-mangling) in C++ code (otherwise you wouldn’t be able to use classes) that you can call in C code by using #include "arduino_c_wrapper.h" and Serial2_begin(...);.

As you can see, that is considerably more work than directly writing a .cpp file and using the classes directly, hence I strongly encourage you to rethink that “I want to write in C and use Arduino” thing. You can easily write C-style code in a .cpp file and never use any C++ features (except for those C++ classes like Serial).

In the end all I did was change extension from serial.c to serial.cpp and it works. Serial2 is receiving and sending fine now without any changes required to header or source code file.