L6218E: Undefined symbol when using separate source file

Hi,
I am stuck with a IMHO very simple task.
I am developing a program under mbed-os 6.4 with an mbed LPC1768. It uses CAN, UART and Circular_Buffers.
The program compiles fine when everything is in main.cpp, but as it got overcrowded, I wanted to move functions from this main.cpp to separate source and header files (slcan.c and slcan.h), which I added to the main directory.
I include the header in main.
Here is the function in slcan.c:

// transform hex nibble to ascii char
char hex2asc(char c)
{
c += 30;
if (c > 39) c += 6;
return c;
}

The C-function “hex2asc” that was “exported” this way can not be linked. I get the following error:

Building project empty-example (LPC1768, ARMC6)
Scan: empty-example
Link: empty-example
[Warning] @0,0: L3912W: Option ‘legacyalign’ is deprecated.
[Error] @0,0: L6218E: Undefined symbol hex2asc(char) (referred from BUILD/LPC1768/ARMC6/main.o).

What is the correct way to add source and header files to a project?

Thanks in advance
Andreas

Hello Andreas,

[Error] @0,0: L6218E: Undefined symbol hex2asc(char) (referred from BUILD/LPC1768/ARMC6/main.o).

It’s probably because the function name hex2asc was mangled by the C++ compiler so the linker is not able to find a function with such name. However it isn’t a C++ function but rather a C one. Try to protect it’s name against C++ mangling in the slcan.h header file for example as follows:

#ifndef SLCAN_H
#define SLCAN_H

#ifdef __cplusplus
extern "C" {
#endif

char hex2asc(char c);

#ifdef __cplusplus
}
#endif

#endif

Best regards, Zoltan

Hello Zoltan,
I thank you for your answer. I sorted this problem out.
Best regards
Andreas