Avoid compiling cpp files if header is not included

Viewed 72

In my C++ project (vscode 1.71.0, platformio core 6.1.4 home 3.4.3 under Ubuntu 22.04) I set up some #define to customize the features of my firmware:

common.h

// App features
#define ENABLE_RTC
#define ENABLE_IRRX
#define ENABLE_DDS
//#define ENABLE_PROXIMITY

Then, in my main.cpp:

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

#ifdef ENABLE_DDS
#inclue "dds.h"
#endif

#ifdef ENABLE_PROXIMITY
#inclue "proxy.h"
#endif

...

Also below in the code there are #ifdef conditions to enable or disable the related part. The problem is even if I don't include an header (like proxy.h in the example above) the compiler still tried to compile the cpp file:

Compiling .pio/build/myproject/src/dds.cpp.o
Compiling .pio/build/myproject/src/proximity.cpp.o

How to tell the compiler to NOT build the source files with no header included?

EDIT

Not sure how to provide more information about the toolchain. It's the default used by vscode+PlatformIO for ESP32.

In the configuration files I can see:

        "cStandard": "c99",
        "cppStandard": "c++11",
        "compilerPath": "/home/mark/.platformio/packages/toolchain-xtensa-esp32/bin/xtensa-esp32-elf-gcc",
        "compilerArgs": [
            "-mlongcalls",
            ""
        ]

Please, feel free to suggest me where to find further information you may need.

1 Answers

Add #ifdef/#endif clauses in your .cpp like it's usually done for headers. It will reduce the compilation to produce an empty *.o file.

In your dds.cpp:

#include "common.h"
#ifdef ENABLE_DDS
...
#endif //EOF
Related