EDIT #1: Added minimal repex, see below:
Background
I'm trying to segment my code into multiple .cpp
files, all of which should have access to an enum
type, which I thought I was declaring in a header file, then including in a number of cpp
files.
However, when I try linking them together, I either get multiple definition
or not defined
errors. I think this stems from my probable misunderstanding of what a declaration is, and what a definition is. I mean I'm clear on this (reference):
- A variable is defined when the compiler allocates the storage for the variable.
- A variable is declared when the compiler is informed that a variable exists (and this is its type); it does not allocate the storage for the variable at that point.
Question
If I have this in my main.h
file, this is clearly just a declaration, isn't it?
#1
enum operation_status {
PRE_START,
RUNNING,
PAUSED
};
How about this one then? Is this a declaration, or a definition?
#2
operation_status op_status;
I would think that this is indeed a declaration, and the definition to go with it would be
#3
op_status = PRE_START;
Thank you in advance for you answers!
Reproducible example:
Main.h
enum operation_status {
PRE_START,
RUNNING,
PAUSED
};
//error given by this: 'multiple definition of op_status'
operation_status op_status;
//error given by this: 'undefined reference to op_status'
extern operation_status op_status;
void changeStatus();
Main.cpp
#include <Arduino.h>
#include <main.h>
void setup() {
op_status = PRE_START;
}
void loop() {
;
}
Change.cpp
#include <main.h>
void changeStatus() {
op_status = RUNNING;
}
What would be the best solution to get around this? Thank you!