A good pattern for removing globals and guaranteeing that the serial port is set up before anything else

Anyone who has worked with Arduino has stuffed things in the global namespace before. To anyone well versed in programming, this is a known bad practice, but it's convenient and it sometimes works so people do it anyhow. It can be responsible for a lot of mysterious bugs that are even harder to track down without the Serial port, which idiomatically gets set up in setup(), after constructors called for an globally visible objects have been called. The hack where you set up Serial in a static constructor also isn't advisable as the order of setup for things defined outside of functions is not guaranteed.

// Constructor gets called before setup(), so anything logged internally is lost. 
// DON'T DO THE FOLLOWING LINE!
// MyObject mySharedObject(/*args_if_any*/); 

struct Globals {
  Globals()
     : mySharedObject(/* args_if_any*/) {}

  // Any mutable data that should persist across runtime should live in here.

  // Do do this.
  MyObject mySharedObject;
};

void setup() {
    Serial.begin(115200);  // Or whatever rate...
}

// You can setup more things inside shared here if you want. Note that the & is 
// really important so you aren't making copies and doing actions that are lost at the 
// end of the function call.
void MySetup(Globals& shared) {...}. 

void MyLoop(Globals& shared) {...}

void loop() {
  Globals shared;
  // Your own defined setup function. 
  MySetup(shared);  

  while(true) {
   // Your own defined loop function. 
   MyLoop(shared);  
  }
}

As your topic relates to Arduino projects and not the Arduino Project itself, which is the forum category that you posted in, it has been moved to a more relevant forum category

Good call. Thanks. I didn't see that when I posted, though I did scroll through the list of options.

Meh. This is one of the things that is different in deep embedded systems run on small and slow microcontrollers. Passing around a structure pseido-globals as you’ve done has little advantage and can slow and bloat the code significantly.

Really? Perhaps I haven't reached that level or maybe I'm not OCD about typing 2 or 3 times what I need and coming up with yet more meaningful names and elegant structures to do simple things.

I’ve never had issues with global variables, so please show us some examples explaining why using them can lead to problems that are (apparently) hard to diagnose, and what changes you would propose for those examples; I’m afraid I didn’t quite follow...

@docdoc and @GoForSmoke

In general it's a good idea to limit the scope of a variable; it prevents that a programming mistake accidentally modifies a variable. But general rules do not always apply to microcontrollers with limited memory.

That's the point.

I’ll fully admit to not being an embedded developer, but I’m not sure I see how passing a pointer around on the stack would be too big of a memory expenditure. Unless I’m working with an ATTiny or something I likely am only using half my memory budget anyhow.

In any case, knowing that all my objects are created after serial is fully initialized saves a lot of debugging headache. Otherwise you’d probably want to write all classes with an Init() method and a minimal constructor, which feels clunky. I’m sure there are folks writing really intense code that would object to doing a lot of OOP on embedded anyhow, but they’re probably also experts in the subject that have debugging hardware and tons of experience in constrained environments. I’m used to larger shared code bases and hope to remain a tourist in embedded land.

It’s ok if there are people for whom this advice isn’t useful, but doing this from the start personally would have saved me a lot of headache in porting code this week, and it felt safer than some of the other advice I’d seen around.

For those that wanted more info on why limiting scope is good, here is an article.

Yes, there are issues with related objects being created out of order. And yes, you can just do global pointers to them and set the order of creation in your setup function. Why all the drama here?

certainly if you're sharing globals between files. Not such a problem within small (< 300 line) arduino programs.

but before c++ in C, weren't classes effectively defined within a file. That file contained global variables and functions. Some functions were exposed in a .h file. Vairables and functions could be prevented from being accessed outside the file by defining them as static

a big benefit of this approach is that changes can be made within the file without changing the .h file, requiring nothing else needing to be recompiled. Changing a C++ class often requires changing the definition in the .h which then requires rebuilding any code including that .h.

so globals aren't necessarily bad practice, just poor use of them is

Yes, this is recommended practice for using classes in Arduino code (except the init() function you suggest is normally called begin() (thus Serial.begin())

Well, the AVR only has 3 index registers (and one of them doesn't allow offsets), and you've just used two of them (one to point to the stack frame, and one to point to your globals.)

Although, for relatively small numbers of arguments, the compiler wouldn't pass arguments on the stack, they'd just go into registers. Which would have to be moved around to use them as pointers.

(and yes, this is also a reason for avoiding the gratuitous use of objects in general, on AVR.)

I made some test code:


void setup() {  NormalGlobalVariable = 5678; }
   0:	8e e2       	ldi	r24, 0x2E	; Load constant
   2:	96 e1       	ldi	r25, 0x16	;  (16bits)
   4:	90 93 00 00 	sts	0x0000, r25	; Store to global register
   8:	80 93 00 00 	sts	0x0000, r24	; 
   c:	08 95       	ret

void MySetup(Globals& shared) {shared.objectifiedGlobal = 1234;};
   e:	22 ed       	ldi	r18, 0xD2	; Load constant
  10:	34 e0       	ldi	r19, 0x04
  12:	fc 01       	movw	r30, r24	; move pointer arg to index reg
  14:	31 83       	std	Z+1, r19	; Store via pointer.
  16:	20 83       	st	Z, r18
  18:	08 95       	ret

The bloat isn't as bad as I thought - those two-word stores are unfortunate. (but there's also the code to load r24 when calling MySetup.)
But MySetup uses 3 times as many registers... (R24, R25 for the argument, r18, r19 for the constant, and r30, r31 (Z) for the ptr.)
(and 1 extra cycle.)

Yeah, I guess it would have been nice if the Arduino code had done stuff to move constructors after the hardware initialization. But it also would have made the code more mysterious to others...

A global in Arduino C++ resolves to a fixed address at link time, before main ever runs, so accessing it takes one instruction with a known address, no lookup, no indirection. On an AVR chip with a couple KB of SRAM shared between globals, heap and stack with zero protection between them, that directness matters.

The cost of avoiding globals shows up in the call chain rather than in the object itself. AVR's calling convention passes the first arguments in a handful of fixed registers, so a pointer or reference threaded through several nested calls occupies one of those registers at every level, forcing the compiler to spill other values to memory or shuffle things around, which costs cycles and code size at each frame. It also means every function in that chain now needs a parameter for something a global would let it reach directly.

There's also the allocation timing question. If you know at compile time you'll need that memory for the life of the program, there's no reason to defer the decision to runtime. A global or static gets its space reserved once and for all before main runs. Runtime allocation only makes sense when the size or lifetime is genuinely unknown, and on Arduino that means malloc or (bad) new pulling from a heap competing with the stack, with no try catch and no stack unwinding to catch a failure gracefully, just a null pointer or a corrupted heap if it fails.

So even when the exact size isn't known ahead of time, the hardware enforces an upper bound anyway, so the fix is the same pattern. Size a fixed buffer to the realistic worst case you want to support, declare it as a global or static, and let it get reserved at compile time. That buys the same guarantee, memory exists before main runs, nothing can fail mid program, no heap fragmentation over a device that might run for months without a reset. It costs you the worst case upfront in your memory budget, which is a better trade than gambling on the allocator succeeding at some unpredictable moment in the field with nothing there to catch the failure and no user watching a screen to report it.

I fully agree with you.

Any rule—especially one that is "rigid" and "absolute" (such as "eliminating global variables")—, in any field, must always be evaluated in light of the specific context and requirements to determine whether it should be applied fully, partially, or not at all.

And in our field (Arduino boards, i.e., microcontrollers), there is no reason to avoid global variables entirely, as factors such as memory management and overall efficiency must be taken into account. I agree that using global variables is not generally considered a "best practice," but every rule should be taken with a grain of salt rather than treated as an infallible, universal "dogma."

To be fair, it sounds like the OP is mostly concerned with global C++ objects which are more complex than simple variables. A global object with a constructor is subject to being problematic if it tries to access hardware (or other objects) that have not be initialized yet. (Serial being a prime example - you can't reference Serial in constructors of global objects (which you might do for debugging, I guess.) (Thus the double "global" and "Serial Port" topic.))

I’m very naughty and tend to use a lot of globals , my reasoning being that I can find them all in the same place . Useful too if you’ve saved values to eeprom you can easily load them all up at start .

I use them so that I only change their values in one place and only read them elsewhere - other wise, I’d agree , it can get confusing.

I’ve had issues before using local static variables not doing what I thought they would!

There's an expression "When in Rome…"

a7

I am on atmega2560 and about half of my project :slight_smile: :

        |   size |   hexa | build/FORTH_c_003.elf
--------+--------+--------+--------------------------
FLASH: 	|  61464 | 0xF018 | data: 628 + text: 60836
RAM:   	|  19892 | 0x4DB4 | data: 628 + bss: 19264

This is because new people (me) to Arduino learn that loop() loops, initializing local variables each time through loop() as well as local variables in functions called by loop() unless the variables are protected using static. Globals "solve" the need to learn how to protect local variables as the internet leads you down a path most travelled... and I am too lazy to read and correct my tens of thousands of sketches.

Declaring a variable each time through loop(), even if is static, has always seemed wasteful to me when the normal mantra is to avoid doing the same thing over and over again, hence the use of global vaiables