Split cpp file, linked to one .h

have header.h and 0.cpp and 1.cpp, both include header.h, I create object in body of 0.cpp, but it is not visible in 1.cpp
The keyword to learn here is 'extern', if you're talking about a global variable.

0.cpp:
1
2
// global scope
Object g_obj;


header.h:
1
2
3
4
5
struct Object { 
    void foo() { }
};

extern Object g_obj;


1.cpp:
1
2
3
4
5
6
7
#include "header.h"

// use obj
void bar()
{
    g_obj.foo();
}


But, when possible, you should try to avoid using global variables. Pass variables through functions when feasible. This isn't always possible if you're working with low-level things like interrupts/poorly-designed callbacks, but it should be a general guideline to strive towards.

(Side-note: Think I found a bug in the formatting on the website...)
Last edited on
Sounds like you aim for global variable. That is almost always unnecessary.

Do show simple case of what you do have. Like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// header.h
#ifndef header_h
#define header_h

struct Foo {
  int x {};
};

int func( const Foo& f );

#endif


// f0.cpp
#include "header.h"

int main(){
  Foo bar {42};
  int answer = func( bar );
}


// f1.cpp
#include "header.h"

int func( const Foo& f ){
  return f.x;
}
If you need information on why there's so much hate for global variables, then here's some reading:

The short version:
https://www.tutorialspoint.com/Why-should-we-avoid-using-global-variables-in-C-Cplusplus
An almost fun in-depth version:
https://thevaluable.dev/global-variable-explained/

They may be useful if you are creating a default state for your class (like cin and cout are objects of the iostream class), but it's worth knowing the downsides to using/providing them.

Please apply namespaces if you choose to use global variables.
Topic archived. No new replies allowed.