Strings in Structs

Hi Everyone,

A question. Can you - or can you not - include Strings in structs?

I have a struct in my main .ino file like this.

struct commandStruct {
    int flags;
    String commandText;
    dvrS commandFunction;
};

and the compiles fine and works when I create a commandStruct later on.

However, when I include the following in an h file.

struct hh_event_def {
  String version ;
};

I get an error:

/src/HH_Event_Defs.h:31:3: error: 'String' does not name a type
   String version ;

So, two questions. Why does it work in the first case and not the second - obviously something to do with scoping, but since the H file is included from the .Ino file - surely it inherits scope…?

The other question is, thinking about this - a struct defines a fixed set of variables which are all pre-typed and have a known size (or a size which is assigned at load time). Whereas, a String type variable is elastic (as it would be in for example Jscript or PHP) and can be expanded and contracted at will (as I understand it) so why is it possible to include it in a struct definition at all? Chalk and cheese surely?

Clearly, there is (at least!) one thing I am not understanding properly here. Can anyone help?

Thanks in advance
Best regards
Alan T in the UK.

In order to have String available in your module, the respective module must #include "Particle.h"

And for completeness, when including a String in a struct you only have the static object members as part of the struct. The actual string content will not be part of the struct, as this is stored in a dynamically allocated mem section on the heap.

BTW, including a header in one file does not mean it’s included the first time in the whole project and since scope won’t be “inherited” in any deterministic way.
For a similar reason you’d need to safeguard against multiple inclusion via #pragma once or a construct like this

#ifndef _SOME_HEADER_
#define _SOME_HEADER_
...
#endif
2 Likes

Right, thank you @ScruffR

As I suspected, some fundamental misunderstandings on my part. Leads to a follow up confirmation though…
My INO file does not include Particle.h - I assume that the cpp file (which I don’t see the contents of in the Web IDE) has that automatically added by the IDE for the “main” module as part of initiation the build process?

Thanks again
Best regards
Alan T.

.ino files do undergo some Wiring preprocessing which does in deed add an #include "Particle.h" instruction to the file before compiling.