1

Hello I am making a private Arduino library but am having trouble understanding how it is linked. Why does this h file work, but when I move the definition of board_led to a matching c file, it throws an error at compilation: In function loop: undefined reference to board_led(bool).

I am using the following board manager to compile in the Arduino IDE: https://raw.githubusercontent.com/maximintegratedmicros/arduino-collateral/master/package_maxim_index.json

I am using the following board target: MAXIM ARM 32bit boards > MAX32630FTHR

#pragma once
#include "Arduino.h"
#include <stdbool.h>
#include <gpio.h>
extern const gpio_cfg_t s_board_led;
extern void board_led(bool on) {
 GPIO_OutPut( &s_board_led, on ? 0 : ~0 );
}
jsotola
1,5342 gold badges12 silver badges20 bronze badges
asked Mar 28, 2022 at 23:40

2 Answers 2

5

I suspect you're compiling from C++ code, and including that header.

When C++ links to C code, the C++ code needs to see extern "C" on the declaration, or surrounding the declaration (via extern "C" { /* function declarations */ })

If you are compiling C++ code against the C code (and linking them together), try making sure extern "C" is used, for example like this:

// arduino_lib.h
#pragma once
#include "Arduino.h"
#include <stdbool.h>
#include <gpio.h>
extern const gpio_cfg_t s_board_led;
extern "C" void board_led(bool on);

While nothing changes in the .c file

// arduino_lib.c
#include "arduino_lib.h"
const gpio_cfg_t s_board_led = /* some value */;
void board_leb(bool on) {
 GPIO_OutPut( &s_board_led, on ? 0 : ~0 );
}
answered Mar 29, 2022 at 0:06
3

To complement Bob's answer it is good practice to add header guards for detecting C++ specifically:

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// your function definitions here
#ifdef __cplusplus
}
#endif // __cplusplus

That way the extern "C" is only applied if the header file is included into a c++ file but not if it's included into a c file.

answered Mar 29, 2022 at 11:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.