Building multiple files

Hi,

I’m new to PlatformIO and i’m trying to build multiple files.

I have in my src folder:

main.cpp:

#include <Arduino.h>
#include "functions.h"

void setup() {
  Serial.begin(9600);
}

void loop() {
  int a = 2, b = 3, c;
  c = multiply(a, b);
  Serial.println(c);
  delay(1000);
}

functions.c:

#include "functions.h"

int multiply (int x, int y)
{
    return (x * y);
}

I have in my include folder:

functions.h:

int multiply (int x, int y);

Everything seems to be correct here but when I try building this, the function multiply in main.cpp is not declared: src/main.cpp:10: undefined reference to `multiply(int, int)’

Can someone help me with this?

When intermixing C with C++ code, you must follow the rules regarding extern "C" declarations for name-mangling. See resourecs like this, this, this and this.

  • this file has no include guard.
  • it does not correctly expose the function to C++ code.

This file needs to be written as

#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_

#ifdef __cplusplus
extern "C"
{
#endif

int multiply (int x, int y);

#ifdef __cplusplus
} // extern "C"
#endif

#endif

to correctly work with C and C++ code.

However, it might be that you don’t want to be writing C code in the first place. Arduino is a C++ framework, and in order to call any of its APIs, you need to writing code in .cpp files, not in .c files. So, I’d rather recommend you fully write the code in C++. Rename functions.c to functions.cpp and the functions.h header to

#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_

int multiply (int x, int y);

#endif

Hi @maxgerhardt

I see, thanks, both your solutions work and I’ve changed my functions.c to a .cpp file.