Multiple files functions

Hi all,

I am trying to migrate from Arduino IDE to PlatformIO on VSCode. I have multiple functions split that use other libraries. I started with a simple case but I am getting the following error:

\src\FFS_functions.cpp.o: In function setupFFS()': FFS_functions.cpp:(.text._Z8setupFFSv+0x5c): undefined reference to channel_X’
FFS_functions.cpp:(.text._Z8setupFFSv+0x68): undefined reference to `channel_Y’

The structure is as follows:
image

And I have the following files:

main.cpp

#include <Arduino.h>
#include <global_vars.h>
#include <FFS_functions.h>

void setup() {
  Serial.begin(115200);
  while(!Serial);
  setupFFS();
}

void loop() {
}

global_vars.h

#ifndef GLOBAL_VARS_H
#define GLOBAL_VARS_H

#include <FFS_Channel.h>

#define DATA_X_PIN 2
#define SCK_X 3
#define ID_X 0
#define DATA_Y_PIN 4
#define SCK_Y 5
#define ID_Y 1

extern FFS_Channel channel_X;
extern FFS_Channel channel_Y;

#endif

FFS_functions.h

#ifndef FFS_functions_h
#define FFS_functions_h

#if ARDUINO >= 100
#include "Arduino.h"
#endif

bool setupFFS(void);

#endif

FFS_functions.cpp

#include <Arduino.h>
#include <global_vars.h>
#include <FFS_functions.h>

bool setupFFS(void){
  channel_X.begin(DATA_X_PIN, SCK_X, ID_X) ? Serial.println("X init") : Serial.println("X fail");
  channel_Y.begin(DATA_Y_PIN, SCK_Y, ID_Y) ? Serial.println("Y init") : Serial.println("Y fail");

  return true;
}

Why am I getting the error? everything should be defined correctly, right?

Thanks in advance!

While you have correctly declared the global variable to be extern, you did not define the variable in a .cpp file. Just add

FFS_Channel channel_X;
FFS_Channel channel_Y;

above your function definition in FFS_functions.cpp.

1 Like

Thanks for the quick reply @maxgerhardt ,

So, I guess that declaring it in the global_vars,h is not sufficient to initialize right?

Correct. A global variable creation needs both the declaration (extern <type> <name>) and definitoin (<type> <name> (<possible constructor arguments / initial value>)).

1 Like

What about initializing other global variables that are shared between main.cpp and FFS_functions.cpp @maxgerhardt ?

should I initialize in main? or on the .cpp functions file?

The location of the definition does not matter – it must be somewhere and only occuring once.

1 Like