1

In C I used to declare global variables like this:

my_C_header.h:

#ifdef my_C_file_C
#define extint
#else
#define extint extern
#endif

extint int32_t my_variable;

I had to include this in my_C_file.c which had a

#define my_C_file_C

at the top. Also I could include it in many other C-files and still had only one instance in memory (and no linker errors).

Now I am using C++17 and read about using inline but I am not sure if that is the correct use case for that. Can I simply write in my_C_header.h:

inline int32_t my_variable;

and have the same effect? Do I need a namespace for that? Searching for this question I get a lot of hits discussing inline static. Does that make sense for a global variable or is it only for class members?

Thanks for any help!

  • 1
    Yes, `inline` makes it as simple as doing `inline int32_t my_variable = some_value;` now. Trying to find a dupe target. – NathanOliver Jun 29 '22 at 12:11
  • I would not recommend global variables. Here is a nice article about that https://levelup.gitconnected.com/alternatives-to-global-variables-34982becfcc. Note I usually use the interface/dependency injection approach since it makes writing my unit tests very easy. – Pepijn Kramer Jun 29 '22 at 12:35
  • I read the first of the mentioned duplicates, it is what I meant with discussing static, so it did not seem to address my question. I am programming embedded devices and want to avoid run time and code size overhead of passing parameters. Thanks to Nathan. – Martin_from_K Jun 30 '22 at 14:25

0 Answers0