Hey everone,
I'm having trouble with what I believe should be fairly straightforward. I'm trying to create a variable in a header file and use it a corresponding .cpp file. the code is a follows:
You also need to decide if that variable needs to be known in multiple files or only in config.cpp.
If only in config.cpp, you can simply declare the variable in the config.cpp instead of in the h file. Or use a different .h file (e.g. config_private.h) and include that file in config.cpp.
You shouldn't be "creating" the variable in the .h file at all. If you need to access that variable from multiple source files (the ONLY reason to have it in a .h file at all), then you must DECLARE it in the .h file. You then #include the .h file into every source file that needs to access the variable. Finally, you must DEFINE that variable as a global in exactly ONE of the source files. And, use Include Guards. Thus:
#include "HeaderFile.h" // #include header in all files that need the variable
uint8_t globalVariable; // Define the variable once and only once
void setup() {
globalVariable = 7; // Use the global variable
.
.
.
}
AnotherFile.cpp:
#include "HeaderFile.h" // #include header in all files that need the variable
void aFunction() { // some function
globalVariable = 2; // Use the global variable
.
.
.
}
AWOL:
You need to #include the file - there is nothing automatic about files with similar names being included.
Duh - thank you! I've been staring at this way too long.
septillion:
Add
#pragma once
at the top of the .h.
Thanks! That's a neat way of handling the guarding instead of the ifndef stuff.
sterretje:
If only in config.cpp, you can simply declare the variable in the config.cpp instead of in the h file. Or use a different .h file (e.g. config_private.h) and include that file in config.cpp.
Thanks! Yes I do need the data to be globally available.
gfvalvo:
You shouldn't be "creating" the variable in the .h file at all. If you need to access that variable from multiple source files (the ONLY reason to have it in a .h file at all), then you must DECLARE it in the .h file. You then #include the .h file into every source file that needs to access the variable. Finally, you must DEFINE that variable as a global in exactly ONE of the source files. And, use Include Guards.
Thank you. That's what I get for having english as a second language. Thank you for the example!
Conclusion:
No - cpp files don't inherit anything from their .h file counterparts. Remember to include those.
Use '#pragma once' in top of header files to be sure they're not included multiple times -> compile errors