Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Help c++ global varibles

Options
  • 29-03-2006 4:11pm
    #1
    Registered Users Posts: 221 ✭✭


    Hi im doing a project in c++ I'm using global varibles in a header file called global.h all the varibes are ints . I keep gettign an eorroe message saying

    "(?gbl"Varible name") already defined in "obj name"

    can anyone tell me whats i'm doing wrong cheers all

    -Elfman


Comments

  • Registered Users Posts: 1,481 ✭✭✭satchmo


    That's caused by more than one translation unit including global.h, and so when they're linked together the same variables are defined twice and so the linker throws that error. You can get around it by using 'inclusion guards'... basically put the code
    #ifndef GLOBAL_H
    #define GLOBAL_H
    
    at the top of global.h, and
    #endif
    
    at the bottom. That way the preprocessor will only include the code in global.h once, and you won't get duplicate variables.

    You should read this article, it explains the whole header/implementation file split pretty well.


  • Registered Users Posts: 2,082 ✭✭✭Tobias Greeshman


    Along with already stated you can include the following line under the preprocessor lines (inclusion guards). It effectively does the same, by only permitting the header file to be included once, thus the code is not compiled multiple times.
    #pragma once
    


Advertisement