Why can I only access public object instances within their own file and not outside?

I am learning about C++ as I go, so bear with me.

In my Arduino project, I have a class declaration at the start of one of my files, Parser.h. In Parser.cpp, I set the variables of the struct declared in Parser.h by iterating through a C string. I have tested this function and I know it performs as intended.

However, the issue begins when I try to refer to Parser.cocktail's variables outside of the Parser.h and Parser.cpp scopes. I have tried a print statement in my main.ino file, as well as in a separate library I made that is also #includeing Parser.h, and neither of them output anything. It's as if they don't see the variables if they're outside the scope, even though they are public.

Parser.h

#ifndef PARSER_H_
#define PARSER_H_
#include <stdio.h>
#include <Arduino.h>

class parser
{
public:
    struct Drink
    {
        char name0[30];
        char name1[30];
        char name2[30];
    };
    Drink cocktail;
    char buffer[250];
    
    void getRecipe();
};

static parser Parser; 

#endif

Parser.cpp

#include "parser.h"
#include <stdio.h>
#include <string.h>
using namespace std;

void parser::getRecipe()
{
    char *p;
    uint8_t n = 0;
    uint8_t iter = 0;
    const char strr[14] = "Hello World !";
    strcpy(buffer, strr);
    for (p = strtok(buffer, " "); p != NULL; p = strtok(NULL, " "))
    {
        if (iter == 0)
        {
            strcpy(Parser.cocktail.name0, p);
            iter++;
        }
        else if (iter == 1)
        {
            strcpy(Parser.cocktail.name1, p);
            iter++;
        }
        else if (iter == 2)
        {
            strcpy(Parser.cocktail.name2, p);
            iter++;
        }
    }
    Serial.println(Parser.cocktail.name0);
    Serial.println(Parser.cocktail.name1);
    Serial.println(Parser.cocktail.name2);
}

main.ino

#include <Arduino.h>
#include <Parser.h>

void setup()
{
  Serial.begin(9600);
  while (!Serial)
  {
    continue;
  }
  Parser.getRecipe();
  Serial.println(Parser.cocktail.name0);
  Serial.println(Parser.cocktail.name1);
  Serial.println(Parser.cocktail.name2);
}

void loop()
{
  
}

This is the Serial output I am getting: site

Hello
World
!

However it should look like:

Hello
World
!
Hello
World
!

Because Serial.println is called 3 times both in main.ino as well as Parser.cpp. The output is coming from Parser.cpp exclusively.

put parser Parser; into the cpp and add extern parser Parser; into .h. this way you will have a single global object of type parser.

now you have two objects one in cpp and one in ino, because both files have static parser Parser; (#include is replaced by the content of the .h)

Yes, this line is our problem:

static parser Parser; 

You get a local instance in each file where you include Parser.h. But you should have only one global instance.

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