"multiple definition of" - Error

I always get this message

I tried to make a minimal code which produces this error

main:

#include "safemode.h"
void setup() {}

void loop() {
 safemode_activator(false);
}

safemode.cpp

#include "safemode.h"

void safemode_activator(bool safemode_status){  
    initiat_timer=true;
}

safemode.h

#ifndef _SAFEMODE_H    
#define _SAFEMODE_H   

void safemode_activator(bool safemode_status);
bool initiat_timer;

#endif // _SAFEMODE_H   

Full error message:

sketch\sketch_jun06b.ino.cpp.o (symbol from plugin): In function setup': (.text+0x0): multiple definition of initiat_timer'
sketch\safemode.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

You include safemode.h in the .ino and in the safemode.cpp file. Therefore two initiat_timer global variables are declared.

Try this:

#include "safemode.h"
void setup() {}

void loop() {
 safemode_activator(false);
}

safemode.cpp

bool initiat_timer;
void safemode_activator(bool safemode_status){  
    initiat_timer=true;
}

safemode.h

#ifndef _SAFEMODE_H    
#define _SAFEMODE_H   

void safemode_activator(bool safemode_status);
extern bool initiat_timer;

#endif // _SAFEMODE_H   

Or have initiate_timer as a return of your function.
Then it does not need to be global over both code files.

Hey thanks for the reply! I have no .ino (or is it self creating?)
The "extern" doesnt work too :frowning: (error undefined reference to `initiat_timer')

If I insert the initiate timer declaration into the .cpp file, it works. But this isnt a good style...

Nonsense. Your understanding is incorrect. See My Post #5 Here for a brief description of the correct way to partition a project into multiple .h / .cpp files.

I believe the more modern C++ style would be this:

#pragma once

void safemode_activator(bool safemode_status);
extern bool initiat_timer;

It's functionally identical but a bit more compact and clear.

1 Like

Yes that is the way I do it professionally. I copied and pasted and was in a hurry but I'm glad you pointed that out. I suspect OP copied and pasted as well.

Wow. 35 years I've been doing it in bad style...

Actually, the philosophy of grouping the methods and data for associated functionality falls under the "cohesion" principal. In this case, this is implemented in C style programming. With C++ you would do the same but use a class to control access to the data. Usually with accessor functions.

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