Using variables cross-header

Jan 2, 2015 at 8:10pm
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
Jan 2, 2015 at 8:59pm
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 Jan 2, 2015 at 8:59pm
Jan 3, 2015 at 2:34pm
Thanks a lot! That'll work out. :)
Jan 3, 2015 at 2:41pm
@ne555 whats the use of #pragma once ?
Jan 3, 2015 at 2:47pm
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.
Jan 5, 2015 at 4:01am
@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 


Jan 5, 2015 at 8:11am
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 Jan 5, 2015 at 8:11am
Jan 5, 2015 at 4:08pm
I see. I get your point there. Okay thank you @MiiNiiPaa you've help me a lot
Topic archived. No new replies allowed.