Thread: Sharing Variables

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    2

    Sharing Variables

    My program consists of several files. Suppose some data and functions in file a must also be accessed by file b. I want to extern these in a header file a.h and #include that in file a and b. This is OK for functions as the extern becomes the prototype when a.h is included in a.c, but with variables you can't have an external reference to a variable in the same file that defines it. What should I do?

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    you can't have an external reference to a variable in the same file that defines it.
    Who says?

    Code:
    itsme@itsme:~/C$ cat extern1.c
    #include <stdio.h>
    #include "myextern.h"
    
    int main(void)
    {
      printf("a in main is %d\n", a);
      foo();
    
      return 0;
    }
    Code:
    itsme@itsme:~/C$ cat extern2.c
    #include <stdio.h>
    #include "myextern.h"
    
    int a = 5;
    
    void foo(void)
    {
      printf("%d\n", a);
    }
    Code:
    itsme@itsme:~/C$ cat myextern.h
    extern void foo(void);
    extern int a;
    itsme@itsme:~/C$ gcc -Wall extern1.c extern2.c -o extern
    itsme@itsme:~/C$ ./extern
    a in main is 5
    5
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    2

    Sharing Variables

    This is just what I wanted to do but my compiler compained that the variable was already declared. Perhaps I was doing something else wrong, I'll go back and look again.
    Many thanks for your help.

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Sounds like you forgot to use the "extern" keyword:

    In .h:
    extern int a;
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  2. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  3. Sharing variables and code architecture
    By JackR in forum C++ Programming
    Replies: 2
    Last Post: 11-30-2007, 04:29 PM
  4. sharing variables between dialogs
    By axr0284 in forum Windows Programming
    Replies: 5
    Last Post: 03-09-2006, 11:42 PM
  5. forking and sharing variables
    By Boomba in forum C Programming
    Replies: 2
    Last Post: 11-20-2005, 08:09 AM