I am running into a problem with compiling in VScode and not when in Visual Studio.
I have a header file config.h
in the include folder in my project. Please note I have added build_flags = -I include
to platformio.ini. In config.h
I need to make some declarations for a select number of global variables that I need. Everything else is done with pointers, etc.
The problem I have is two fold.
int myVar
in config.h I get a multiple declaration error. Why?extern int myVar
. But then I need to redeclare the variable myVar in a .cpp file, like main.cpp. How is this best done?Ultimately, how can I declare a global variable in a header, include that header in several other files and then use the variable globally? (This is primarily aimed at creating queues and semaphores)
If you just want global constants, refer to Defining global constant in C++. Assuming that you need a mutable global variable, there are two options. In either case, there will be only one instance of our global variable.
extern
// header file
extern MyQueue queue;
Here, we simply say that queue
is defined in some other source file.
// source file
MyQueue queue{1, 2, 3};
And then, we define it in the source file. Also see cppreference on external linkage
inline
// header file (no source file needed)
inline MyQueue queue{1, 2, 3};
inline
works the same for functions as it does for variables. It relaxes the one definition rule (ODR) for our variable, allowing us to define it in multiple locations. This way, we don't get any linker errors when including the header in multiple source files.