0

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.

  1. When declaring a variable for example int myVar in config.h I get a multiple declaration error. Why?
  2. I can declare the variable as 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)

rioV8
  • 24,506
  • 3
  • 32
  • 49
Misha
  • 556
  • 1
  • 8
  • 25
  • Go with the `extern int myVar` option. Yes, you have to redefine `myVar` in all .cpp files. – Talal02 May 06 '21 at 17:30
  • You don't need to **redeclare** the variable in a .cpp file; you need to **define** it in a .cpp file. A **declaration** says "there's a variable somewhere with this name and this type". A definition says "this is a variable with this name and this type". You can have as many declarations as you like for a variable; you can only have one definition. – Pete Becker May 06 '21 at 17:31
  • Thanks for the replies. To keep things simple, should I create an accompanying config.cpp file that then defines the variable? Id like to keep modularity as much as possible. – Misha May 06 '21 at 17:36

1 Answers1

2

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.

Classic Solution: 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

C++17 Solution: 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.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96