Using variables cross-header

Hello

Is there a way to use variables cross-header in C++?

Example: main.cpp:
1
2
3
4
5
6
7
#include <iostream>

using namespace std;
int main() {
string myStr = "Test123";
display();
}


test.h:
1
2
3
void display() {
cout<<myStr<<endl;
}


Any way to achieve this?

Thanks for reading,
Niely
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//test.h
#ifndef TEST_H //header guard
#define TEST_H
#pragma once //alternative

#include <iostream> //to use cout
#include <string> //to use string

//you cannot have function definition in headers (except if they are inline or template)
inline display(std::string s){
   std::cout << s << std::endl;
}

#endif 

1
2
3
4
5
6
7
8
9
//main.cpp
#include "test.h" //to use display()
#include <string> //to use string

int main(){
   std::string foo = "bar";
   display( "Test123" );
   display( foo );
}
Last edited on
Thanks a lot! That'll work out. :)
@ne555 whats the use of #pragma once ?
Lorence30 wrote:
@ne555 whats the use of #pragma once ?
This is non-standard by widely supported extension which works like header guards, but often has added bonuses (like not even opening that file second time). However many compilers can recognise header guards and add tose bonuses to them as well.
@MiiNiPaa
This is non-standard by widely supported extension which works like header guards


i see, and theres a lot advantage by using it base on my research.
last,
isnt it more good if you only use one?
example:
#pragma once

than this
1
2
3
4
5
 #ifndef HEADER_H_INCLUDED
          #define HEADER_H_INCLUDED
#pragma once
  //declaration
#endif 


isnt it more good if you only use one?
What if you decide to compile your program on compiler which does not support #pragma once ? It is better to have it in addition to standard way of doing this. I usually do not even care, as many compilers extend it advantages to header guards too and for historical reasons (pragma once did not work on two different files with same content)
Last edited on
I see. I get your point there. Okay thank you @MiiNiiPaa you've help me a lot
Topic archived. No new replies allowed.