How to use own header files

Hello,

my goal is to add my own header file with its declaration file, eg. interface.h + interface.c. The purpose of these files is to outsource the code from the main.cpp file.

For that I created the both files with a simple function call from the main.cpp in PlatformIO Arduino.

main.cpp:

#include <Arduino.h>
#include “interface.h”
void setup() {
}

void loop() {
RelayOn(true);
}

interface.h:

#include <Arduino.h>
void RelayOn(bool OnState);

interface.c

#include “interface.h”
//GPIO for relay
#define CONTROL_GPIO 26
#define CONTROL_GPIO_OFF_STATE 0
#define CONTROL_GPIO_ON_STATE 1

//# Interface #
void RelayOn(bool OnState) //switch relay
{
if (OnState)
digitalWrite(CONTROL_GPIO, CONTROL_GPIO_ON_STATE);
else
digitalWrite(CONTROL_GPIO, CONTROL_GPIO_OFF_STATE);
}

File structure:
io

I do not have any errors in the editor preview, but when I try to compile I receive an error message:

LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 33 compatible libraries
Scanning dependencies...
Dependency Graph
|-- interface
Building in release mode
Linking .pio\build\esp-wrover-kit\firmware.elf
c:/users/home/.platformio/packages/toolchain-xtensa-esp32/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: .pio\build\esp-wrover-kit\src\main.cpp.o:(.literal._Z4loopv+0x0): undefined reference to `RelayOn(bool)'
c:/users/home/.platformio/packages/toolchain-xtensa-esp32/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: .pio\build\esp-wrover-kit\src\main.cpp.o: in function `loop()':
C:\Users\Home\OneDrive\Dokumente\PlatformIO\Projects\Test/src/main.cpp:8: undefined reference to `RelayOn(bool)'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\esp-wrover-kit\firmware.elf] Error 1

Any help on that what I’m doing wrong would be very helpfull.

Thanks in advance
Alex

Your file, interface.c will be compiled by the C compiler. The file, main.cpp will be compiled by the C++ compiler. They do different things to function names. Because C++ allows you to override functions provided there are differences in the parameters, the C++ compiler mangles the function name to reflect the function name and parameters. The C compiler doesn’t.

At the moment, your RelayOn function is sitting in an object file with exactly that name, RelayOn. The C++ compiler has created a function call to something like RelayOnBool which the linker cannot find, and the linker is the one complaining.

You should rename your interface.c to interface.cpp and then all will be well.

Note: Poetic Licence has been used in the above explanation, but that’s basically what’s gone wrong. :wink:

HTH

Cheers,
Norm.ot

1 Like