Importing headers outside main.cpp

I’m trying to write a simple bluetooth project to get used to the PlatformIO style after having programmed both with the Arduino IDE and using ESP-IDF. I am developing on an esp32 using the Arduino framework. The project runs fine when I run it all in the main.cpp file, but as soon as I try to separate the bluetooth code into its own module compilation fails. It seems that I can’t

#include “BluetoothSerial.h”

in my new module. What must I do to be able to import headers outside the main.cpp file?

Define “own module”. Where do you put which exact code?

I follow the README instructions which state

The lib directory is for project specific (private) libraries.

And I follow the conventions stated in the README, so my module looks like:
– lib
---- Bluetooth
------ src
-------- bluetooth.h
-------- bluetooth.c

The errors I have are in the bluetooth.c file when I try to import BluetoothSerial.h.

It should be:

#include "BluetoothSerial.h"

#import is not valid in C/C++ code (except in cases not relevant here).

Furthermore, BluetoothSerial.h declares a C++ class. So it will only work when included from C++ code.

Sorry about that, it was just a typo in the original question. I am using:

#include “BluetoothSerial.h”

I have edited the question for clarity. To clarify further, the code doesn’t complain about the #include statement, it complains when I declare a BluetoothSerial variable and when I try to use that same variable. eg:

BluetoothSerial btSerial;
btSerial.begin(“ESP32-test”);

both these lines fail.

What did fix the issue was the last paragraph in your answer. The error was I was trying to use the class in a file bluetooth.c instead of a bluetooth.cpp file. I can’t believe I hadn’t noticed that sooner.

Thank you very much for your help. :slight_smile:

It would be helpful if you provided more information, in particular the full error message.

But again: BluetoothSerial is a C++ class and you are trying to use it from a C file. Rename bluetooth.c to bluetooth.cpp.

1 Like