r/arduino • Prolific Helper • 19d ago

Solved! I've forgotten how access variable in different .cpp

I have the following definition in one .cpp file :

static char cfgv_var_weather_icon[10] = "";

How do I set it from another .cpp file? BTW, the code was generated by LCD Wizard, not me.

All I get is red, mysterious compiler errors.

0 Upvotes

5 comments sorted by

9

u/gm310509 400K , 500K , 600K , 640K , 750K 19d ago

In the other C file you use the extern modifier:

extern char cfgv_var_weather_icon[];

Also, you need to remove the static keyword, that will make it private.

And, if it is declared inside the body of a function you need to move it outside the function

1

u/madsci 18d ago

static means the variable is specifically not to be visible to other modules. Before you change that and start accessing it from somewhere else, you should look into why that variable is static. Usually that means "this variable is for internal use only - don't touch".

If this is part of a configuration and you want to move the configuration somewhere else then you can change static to extern and the declare it in your own configuration file.

-2

u/Ok_Spare_7473 18d ago

Why don't you ask GPT about this?
Just use inline (c++) construction or extern (C-lang).

0

u/BobsYourUncle_8192 Prolific Helper 18d ago

I did and I took u/gm310509's advice as well. In retrospect, I feel stupid for asking it in the first place. It's just been a long time since I did projects with multiple .cpp files and variables all over the place. Usually my Arduino projects are all-in-one.

1

u/gm310509 400K , 500K , 600K , 640K , 750K 18d ago

LOL, we all forget stuff.

A few months ago, one of my .cpp (or .c - I can't remember) was generating a huge number of errors. More errors than there were lines in the file (it was maybe 100 lines of code).

The project consisted of several .cpp, .c and some .S files along with their headers.

I spent a whole day trying to figure out why just this one source file was generating so many errors. Evenentually I threw in the towel and asked online.

The replies were immediate and accurate and of the form:

You should #include the ".h" file, not the ".c" file

Doh! I quite literally could not see that particular forest because of all the trees getting in the way.