PlatformIO Community

Newbie needs help VSCODE ESP32 Arduino project

Hi,
I am working on a ESP32 project to run on ESP32 using PlatformIO in VSCODE.
I have a very basic problem that the compiler is complaining it cannot find a routine I am trying to call from main.
The routine is in a “C” file with declaration in “h” file (both saved in “src” folder).

In workspace.code-workspace, I see the file association for my module as below.
{

"folders": [

    {

        "path": ".."

    }

],

"settings": {

    "files.associations": {

        "uart.h": "c"

    }

}

}

I have "#include “uart.h” in main.cpp
The declaration for the routine in uart.h is … void uart_init(void);

Error is given
Linking .pio\build\esp32dev\firmware.elf
.pio\build\esp32dev\src\main.cpp.o:(.literal._Z5setupv+0x60): undefined reference to uart_init()' .pio\build\esp32dev\src\main.cpp.o: In function setup()’:
D:\Firmware\temp\Test_LED/src/main.cpp:249: undefined reference to `uart_init()’

Since you’re mixing C and C++ code (why not write everything in C++?) you need to take care of name mangling. Your uart.h file should take care to add extern "C" in the function declaration if the header is included by a .cpp file so that the C++ code sees it as in-C implemented function with its appropriate symbol name. This is explained e.g. here. uart.h should look like

#ifndef MY_UART_H_
#define MY_UART_H_

#ifdef __cplusplus
extern "C" {
#endif

void uart_init(void);

#ifdef __cplusplus
}
#endif

#endif /* MY_UART_H_ */

Thanks Max,

I managed to get it to compile. I had another error but it was not function declaration issue, It was an external reference to semaphore I did not create in main.

My main module has a combination of esp-idf (“C”) code and arduino code. Can I do same in modules. and simply rename uart.c as uart.cpp?

ESP-IDF headers are safe to be included from C++ code without any code changes needed in comparison to C regarding the inclusion, so this should work.