Thread: variables in 1 header, accessible to different c files

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    269

    variables in 1 header, accessible to different c files

    Hi,

    I have a header (call it a.h) file where I declare some variables, such as an int. For example

    Code:
    int ranks;
    I have a .c file (call it a.c) that implements the function prototypes of that header file. It also uses those variables for different reasons.

    In another .c file (call it b.c), I include a.h and and include the a.o when i'm linking.

    now, in b.c I want to assign a value to this variable ranks (found in a.h) simply by doing

    Code:
    ranks = total_ranks;
    or something like that. However, when running the code and printing, total_ranks is correct (say 10), but ranks is always 0 when printed in a.c.

    Where should I put this int ranks ??

    Thank you!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    You should put
    int ranks;
    in exactly ONE .c file (doesn't matter which)

    You should put
    extern int ranks;
    in your .h file, and include it in all the files which need to access ranks.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    269
    Got it... in a.h I have to do

    Code:
    extern int ranks;
    and in the a.c I have to do

    Code:
    int ranks;
    Now it's accessible. thank you!!

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    269
    You are correct. thanks so much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Static variables and header files
    By drrngrvy in forum C++ Programming
    Replies: 8
    Last Post: 12-02-2006, 01:27 PM
  2. Replies: 3
    Last Post: 11-28-2006, 03:44 PM
  3. Variables in header files
    By Overlord in forum C++ Programming
    Replies: 5
    Last Post: 10-15-2006, 06:43 AM
  4. Linking header files, Source files and main program(Accel. C++)
    By Daniel Primed in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 11:46 AM
  5. include library header in header files
    By Raison in forum C++ Programming
    Replies: 6
    Last Post: 09-27-2004, 02:50 AM