Git submodule in lib directory using .c files

Hi, I am trying to manage a multi pronged project of which a Particle Boron is a part. There are three other microcontrollers used in conjunction with the Boron, and two different IDEs in addition to Visual Studio code to manage.

The git submodule is meant to be the glue that holds everything together and keeps things consistent. However, two of the IDEs (Segger and STM32CubeIDE) are not setup for c++, and I can't get Visual Studio code to compile a .c file. There is no actual need for C++ features in the glue code.

Is there a way to make this work without using a script or something to automatically change the filename extensions to match what each environment wants?

Which compiler (cloud or local) are you using in Workbench? You can definitely compile .c files in Workbench local compile. And I think cloud compile should work, at least in recent versions of Device OS.

What you can't do is #include Particle.h, Arduino.h, or application.h. These header files require C++ compilation.

What I do for the C glue files is only use C native types (int, unsigned long, etc.) instead of the other types that may require the Particle header (uint32_t, etc.) for all of the cross-platform interfaces.

I am using the local compiler. The C files I am including are just a simple test case:

//test_c.h
#ifndef TEST_C
#define TEST_C

int getNumber();

#endif

and

//test_c.c
#include "test_c.h"

static int number = 8;

int getNumber()
{
  return number;
}

When I compile with the file named test_c.c, it does not work - I get the error "project.ino:308: undefined reference to `getNumber()'"

It works if I rename test_c.c to test_c.cpp. In the worse case scenario I will just include a script in my submodule that renames files back and forth between .c and .cpp, but that is annoyingly hacky.

In test_c.h you need to declare the function as having C linkage, like this:

//test_c.h
#ifndef TEST_C
#define TEST_C

#ifdef __cplusplus
extern "C" {
#endif

int getNumber();

#ifdef __cplusplus
}
#endif

#endif

What this does is prevent C++ name mangling, which also prevents overloaded function names from working, but it is compatible with both C and C++.

1 Like

Thank you so much! That solved my problem.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.