Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Sharing variable in different files  (Read 3040 times)

0 Members and 1 Guest are viewing this topic.

iHope

  • Newbie
  • *
  • Posts: 35
    • View Profile
Sharing variable in different files
« on: February 06, 2012, 04:57:33 pm »
So, I'm really puzzled right now. I would need to get my sf::Shape X to be global, so I could use it in different file. X is in file x.cpp & x.hpp, but I need to get it usable in y.cpp. I heard that global variables could help, but everyone keeps saying they're bad. Help would be really appreciated

Again sorry about my english and asking such a stupid questions :oops:

HKei

  • Newbie
  • *
  • Posts: 23
    • View Profile
Sharing variable in different files
« Reply #1 on: February 06, 2012, 06:35:03 pm »
Your english isn't really a problem.

Anyways: Have you thought about that maybe you don't actually need a global variable if you just look at the problem from a slightly different view point?

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Sharing variable in different files
« Reply #2 on: February 06, 2012, 07:14:14 pm »
Why don't you pass the variable to different files via functions (as parameters) and classes (as members)?
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

mateandmetal

  • Full Member
  • ***
  • Posts: 171
  • The bird is the word
    • View Profile
    • my blog
Sharing variable in different files
« Reply #3 on: February 06, 2012, 08:07:27 pm »
you could use

extern var_type var_name;

in your y.cpp file (probably not the best solution)
- Mate (beverage) addict
- Heavy metal addict _lml
- SFML 2 addict
- My first (and free) game: BichingISH!

iHope

  • Newbie
  • *
  • Posts: 35
    • View Profile
Sharing variable in different files
« Reply #4 on: February 06, 2012, 09:13:18 pm »
Okay, thanks for your tips. The main problem is that the "variable" is sf::Shape. I tried to use extern, but it doesn't work(dunno doing something wrong or it just doesn't work).

texus

  • Hero Member
  • *****
  • Posts: 505
    • View Profile
    • TGUI
    • Email
Sharing variable in different files
« Reply #5 on: February 06, 2012, 09:35:16 pm »
You shouldn't use it as extern.

Do as Nexus said: pass the variable with the function or put all your variables in a class.
I would do the second thing. Make an instance to the class in your main function and from then you only work with the functions and variables inside that class.
TGUI: C++ SFML GUI

iHope

  • Newbie
  • *
  • Posts: 35
    • View Profile
Sharing variable in different files
« Reply #6 on: February 07, 2012, 06:47:07 am »
Thank you! I need to check out how to do that, what you explained. :D

 

anything